Sean
Sean

Reputation: 3052

std::bad_weak_ptr exception in shared_from_this after object construction

I have a class defined similar to the following:

class A : std::enable_shared_from_this<A> {
public: 
  static std::shared_ptr<A> create() {
    return std::shared_ptr<A>(new A());
  }

  void f() { 
    shared_from_this();
  }

private:
  A() { }
};

and it's used similarly to:

std::shared_ptr<A> pt = A::create();
pt->f();

Despite the call to shared_from_this() being called after the shared_ptr pt is created, the call to f() still results in a bad_weak_ptr exception being thrown. Running it in gdb confirms that the exception is thrown on the call to f() and not in some code I haven't included here that's called by the instructor.

Upvotes: 1

Views: 1420

Answers (2)

GSAT
GSAT

Reputation: 56

Public inheritance is required here. As it is class A , hence it is not default. So is the reason for seeing the exception/ bad_weak_ptr.

Upvotes: 1

Brian Bi
Brian Bi

Reputation: 119089

std::enable_shared_from_this<A> must be a public base. When the shared_ptr constructor sees that you've derived from enable_shared_from_this, it stores a weak copy of itself inside the enable_shared_from_this object. If the inheritance is not public, this cannot occur, and the weak_ptr stored inside the enable_shared_from_this will be null, leading to the bad_weak_ptr exception when shared_from_this later tries to construct a shared_ptr from it.

Upvotes: 8

Related Questions