我有一個接口實現的中央列表,並希望派生類能夠在列表中註冊自己,而無需將它們添加到某個中心位置。例如:在中央列表中註冊派生類
// interface.h
struct MyInterface;
std::vector<MyInterface*>& InterfaceList();
struct MyInterface {
MyInterface() {
InterfaceList().push_back(this);
}
virtual ~MyInterface() {}
// ...
};
// derived.cpp
#include "interface.h"
class MyImplementation: public MyInterface {
public:
MyImplementation() {
}
// ...
};
MyImplementation impl;
這似乎不起作用。由於我不明白的原因,MyInterface的構造函數永遠不會被調用 - 我會認爲派生類的實例會在啓動時調用它。我知道可以沿着這些方向做些事情,因爲我已經看到了其他庫這樣做 - 但還沒有設法弄清楚我做錯了什麼。
謝謝:)
編輯:對不起,錯過了對大括號和參考的。 InterfaceList()是一個函數,它返回一個向量的引用。
編輯第2部分:現在已經在一個簡化的例子中工作,但無法讓它在派生實現的文件中工作 - 但該技術正在另一個項目中工作。這些文件中必然會有一些細節上的差異,但這似乎不是我發佈的代碼中的問題。雖然我不想真的想張貼僱主項目的大片,所以我想我必須不停地擺弄自己。感謝您的建議,到目前爲止雖然:)
你的虛擬dtor在哪裏?你需要一個在你的基類。 – 2010-06-23 04:42:23
Anders:我正在嘗試發佈代碼的簡化版本,因此也留下了一些小部分。爲了討論的目的,我不在乎它是否泄漏內存:) – Peter 2010-06-23 04:55:20