class BB
{
public:
BB()
{
printf("BB Creator\n");
fflush(stdout);
}
virtual void DoNothing()
{}
};
typedef BB* (*CreateA)();
CreateA creata = 0;
template<class T>
class A
{
public:
A()
{
printf("A Creator\n");
fflush(stdout);
creata = Create;
}
static BB* Create()
{
return new T();
}
void DoNothing(){}
};
template<class T>
class B : public BB
{
public:
B()
{
printf("B Creator\n");
fflush(stdout);
}
public:
virtual void DoNothing()
{
a.DoNothing();
}
public:
static A<T> a;
};
template<class T>
A<T> B<T>::a;
class C :public B<C>
{
public:
//C() {} 如果加上这句就对了 但是去掉以后似乎父类的构造函数都被优化掉了
};
class D
{
public:
void DFunc()
{
bb = (*creata)();
}
public:
BB* bb;
};
int main()
{
D d;
d.DFunc();
return 0;
}
如果在VS下编译是可以正确执行的
在GCC下则不行 因为作为静态成员的A B::a;没有生成, A的构造函数没有被调用, creata 则为空指针