例如
//somewhere
struct IFace;
struct Base
{
Base(IFace* iface):
f(iface)
{
//will not use iface here
}
private:
IFace* f;
};
struct Data;
struct Implementation
{
private:
friend IFace* factory_create(Data*);
Implementation(Data* data): // ok, it's not private, just some internal
// class not mentioned in public headers
d(data)
{
//will not deref data here
}
private:
Data* d;
};
IFace* factory_create(Data* data)
{
return new Implementation(data);
}
//here
struct Derived: Base
{
Derived():
Base(factory_create(&data)) //using pointer to uninitialized member
{
//will fill data here
}
Data data;
};
data
似乎在将指针传递给它之前我没有机会创建它factory_create
。
这段代码安全吗?如果不是,我应该做哪些最小的改变来保证它的安全?