从构造函数初始化列表传递 [英] passing this from constructor initializer list
问题描述
在以下代码中将this传递给初始化器列表中的另一个对象时,是否有任何问题?
Are there any issues when passing 'this' to another object in the initializer list in the following code?
class Callback { public: virtual void DoCallback() = 0; };
class B
{
Callback& cb;
public:
B(Callback& callback) : cb(callback) {}
void StartThread();
static void Thread()
{
while (!Shutdown())
{
WaitForSomething();
cb.DoCallback();
}
}
};
class A : public Callback
{
B b;
public:
A() : b(*this) {b.StartThread();}
void DoCallback() {}
};
如果这样做不安全,最好的选择是什么?
If it is unsafe to do that, what's the best alternative?
推荐答案
如果你非常小心,这将工作正常。如果你开始调用虚方法或使用依赖于类型中其他对象的方法,你会遇到很多麻烦。但是如果你只是设置一个引用,这应该工作正常。
If you are extremely careful this will work fine. You will get into a lot of trouble if you start calling virtual methods or using methods which depend on other objects in the type. But if you're just setting a reference this should work fine.
一个更安全(但不完全安全)的替代方法是一旦构造函数完成后再设置b。这不会消除vtable问题,但会消除在构建之前访问其他成员变量的问题。
A safer (but not completely safe) alternative is to set b later on once the constructor is completed. This won't eliminate vtable issues but will remove problems like accessing other member variables before they are constructed.
class A : public Callback {
std::auto_ptr<B> spB;
public:
A() {
spB.reset(new B(this));
spB->StartThread();
}
};
这篇关于从构造函数初始化列表传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!