Bug 57228 - [c++11] constructing shared_ptr to enable_shared_from_this-derived class from raw pointers
Summary: [c++11] constructing shared_ptr to enable_shared_from_this-derived class from...
Status: RESOLVED INVALID
Alias: None
Product: gcc
Classification: Unclassified
Component: libstdc++ (show other bugs)
Version: 4.7.2
: P3 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2013-05-09 14:02 UTC by Frank Heckenbach
Modified: 2013-05-09 14:16 UTC (History)
0 users

See Also:
Host:
Target:
Build:
Known to work:
Known to fail:
Last reconfirmed:


Attachments
Test case (166 bytes, text/x-c++src)
2013-05-09 14:02 UTC, Frank Heckenbach
Details

Note You need to log in before you can comment on or make changes to this bug.
Description Frank Heckenbach 2013-05-09 14:02:12 UTC
Created attachment 30076 [details]
Test case

http://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr says:
"When constructing a shared_ptr from a raw pointer to an object of a
type derived from std::enable_shared_from_this, the constructors of
shared_ptr detect other owners of the object through the weak
reference stored in that base class. This allows ownership of the
object to be shared with existing shared_ptrs. Otherwise, it is
undefined behavior to construct a shared_ptr for an object that is
already managed by another shared_ptr."

Therefore, I gather the attached program should share ownership,
but it doesn't: It says "gp2.use_count() = 1;" and aborts due to
double deletion.

Using shared_from_this() works, though, so it's probably not a
serious problem.
Comment 1 Jonathan Wakely 2013-05-09 14:10:54 UTC
cppreference is wrong.

This exact case has been discussed on the LWG reflector and everyone agreed it's invalid.  The shared_ptr(Y*) constructor use_count() == 1 as a postcondition, which is not compatible with the claim that you can share ownership with existing shared_ptr objects.
Comment 2 Jonathan Wakely 2013-05-09 14:16:47 UTC
This is http://cplusplus.github.io/LWG/lwg-active.html#2179 but if the behaviour changes I'll eat my hat.