我正在研究一个遗留框架。假设“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))
{ }
};
有关相同内容的更多讨论,请参见clc++.m上的此链接。Konstantin Oznobikhin 给出了一个很好的通用解决方案。