我正在使用遺留的框架。可以說'A'是基類,'B'是派生類。這兩個類都執行一些關鍵的框架初始化。 FWIW,它大量使用ACE庫。衍生類構造函數問題的依賴關係
我有一種情況,其中; 'B'的一個實例被創建。但'A'的Ctor取決於一些只能從'B'執行的初始化。
正如我們知道'B'實例化時'A'的Ctor在'B'之前被調用。 virtual
機制不能從ctors工作,使用static functions
被排除(由於static-initialization-order-fiasco)。
我認爲使用CRTP模式如下: -
template<class Derived>
class A {
public:
A(){
static_cast<Derived*>(this)->fun();
}
};
class B : public A<B> {
public:
B() : a(0) {
a = 10;
}
void fun() { std::cout << "Init Function, Variable a = " << a << std::endl; }
private:
int a;
};
但是,這是在初始化列表中初始化的類成員,因爲他們尚未執行(FE「A」在上述情況下未定義的值)。在我的情況下,有很多這樣的基於框架的初始化變量。
是否有任何知名的模式來處理這種情況?
由於提前,
更新:
基於由dribeas給出的主意,我喚出行動這一問題的臨時解決方案(一個完整的重構呢現在不符合我的時間表)。下面的代碼將表現出同樣的: -
// move all A's dependent data in 'B' to a new class 'C'.
class C {
public:
C() : a(10)
{ }
int getA() { return a; }
private:
int a;
};
// enhance class A's ctor with a pointer to the newly split class
class A {
public:
A(C* cptr)
{
std::cout << "O.K. B's Init Data From C:- " << cptr->getA() <<
std::endl;
}
};
// now modify the actual derived class 'B' as follows
class B : public C, public A {
public:
B()
: A(static_cast<C*>(this))
{ }
};
有關同一些更多的討論見c.l.C++米this鏈接。 Konstantin Oznobikhin給出了一個很好的通用解決方案。
即UB(未定義行爲)和一個相當惡劣的伎倆編譯器播放。 – 2010-01-12 08:29:01