C++ – passing this from constructor initializer list

c++

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?

Best Solution

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.

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();
  }
};