This page is a snapshot from the LWG issues list, see the Library Active Issues List for more information and the meaning of Resolved status.

2529. Assigning to enable_shared_from_this::__weak_this twice

Section: [util.smartptr.enab] Status: Resolved Submitter: Jonathan Wakely Opened: 2015-08-26 Last modified: 2020-09-06

Priority: 3

View all other issues in [util.smartptr.enab].

View all issues with Resolved status.


It is unclear what should happen if a pointer to an object with an enable_shared_from_this base is passed to two different shared_ptr constructors.

#include <memory>

using namespace std;

int main()
  struct X : public enable_shared_from_this<X> { };
  auto xraw = new X;
  shared_ptr<X> xp1(xraw);  // #1
    shared_ptr<X> xp2(xraw, [](void*) { });  // #2
  xraw->shared_from_this();  // #3

This is similar to LWG 2179, but involves no undefined behaviour due to the no-op deleter, and the question is not whether the second shared_ptr should share ownership with the first, but which shared_ptr shares ownership with the enable_shared_from_this::__weak_this member.

With all three of the major std::shared_ptr implementations the xp2 constructor modifies the __weak_this member so the last line of the program throws bad_weak_ptr, even though all the requirements on the shared_from_this() function are met ( [util.smartptr.enab])/7:

Requires: enable_shared_from_this<T> shall be an accessible base class of T. *this shall be a subobject of an object t of type T. There shall be at least one shared_ptr instance p that owns &t.

Boost doesn't update __weak_this, leaving it sharing with xp1, so the program doesn't throw. That change was made to boost::enable_shared_from_this because someone reported exactly this issue as a bug, see Boost issue 2584.

On the reflector Peter Dimov explained that there are real-world use cases that rely on the Boost behaviour, and none which rely on the behaviour of the current std::shared_ptr implementations. We should specify the behaviour of enable_shared_from_this more precisely, and resolve this issue one way or another.

[2016-03-16, Alisdair comments]

This issues should be closed as Resolved by paper p0033r1 at Jacksonville.

Proposed resolution: