Title
Assigning to enable_shared_from_this::__weak_this twice
Status
resolved
Section
[util.smartptr.enab]
Submitter
Jonathan Wakely

Created on 2015-08-26.00:00:00 last changed 96 months ago

Messages

Date: 2016-03-15.00:00:00

[ 2016-03-16, Alisdair comments ]

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

Date: 2015-08-26.00:00:00

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.

History
Date User Action Args
2016-05-06 15:21:52adminsetmessages: + msg8073
2016-05-06 15:21:52adminsetstatus: new -> resolved
2015-08-26 00:00:00admincreate