Re: Valid use of shared_ptr?
kwikius wrote:
Is the following a valid use of shared_ptr?
What I want to do is to be able to create a class on the heap or on the
stack using shared_ptr, but also to be able to get a shared_ptr to it
irrespective of whether it is on the stack or heap.
The following seems to work, if USE_DUMMY_SHARED_POINTER is defined,
but is it correct?
The specification doesn't say what happens with the
enable_shared_from_this base when you construct two shared_ptr
instances from the same raw pointer. In your case, when the statement
my::ptr x_ptr = my::ptr(new my());
is executed, my::my initializes the enable_shared_from_this base with
my::dummy_shared_ptr, then the constructor of x_ptr initializes it a
second time with x_ptr. It will work in practice unless the
implementation decides to intentionally stop you (but depending on
which initialization wins you may not be getting a copy of x_ptr from
get_ptr). One way to do it "by the book" is to define the dummy pointer
explicitly whenever the object is created on the stack:
my x;
my::ptr dummy_x_ptr( &x, null_deleter() );
This doesn't solve the problem with someone keeping a shared_ptr to
your stack-allocated object, though. Usually, holding a shared_ptr is a
guarantee that the object will stay alive, so allowing people to obtain
a shared_ptr to a stack-allocated object may violate their
expectations. It will work (MT issues aside) if they hold a weak_ptr.
Another approach is to just hand people a copy of the dummy_shared_ptr
member, if the above issue is not a problem for some reason, as shown
in
http://www.boost.org/libs/smart_ptr/sp_techniques.html#weak_without_shared
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]