$include_dir="/home/hyper-archives/boost/include"; include("$include_dir/msg-header.inc") ?>
Subject: Re: [boost] [SmartPtr] alternative to enable_shared_from_this
From: Gavin Lambert (gavinl_at_[hidden])
Date: 2017-01-16 02:24:24
On 6/01/2017 06:50, Roberto Hinz wrote:
> hmm, I didn't know enable_shared_from_raw until now. Still, can
> shared_handle be an alternative to enable_shared_from_raw ?
>
> enable_shared_from_raw has been criticized of been too prone to cause
> memory leaks [1] .
>
> [1]
> http://stackoverflow.com/questions/22184772/why-is-boostenable-shared-from-raw-so-undocumented
The point there is that if you inherit enable_shared_from_raw and then
provide some way to obtain a non-shared pointer to the object (ie. you
don't use something like the shared factory pattern to guarantee that
the object can't be constructed without a shared_ptr) then it will leak
memory if you do so. (In much the same way that setting up a pointer
cycle will leak memory, except on a smaller scale.)
Conversely, if you inherit enable_shared_from_this and similarly provide
some way to obtain a non-shared pointer to the object, then calling any
method that assumes that there is a shared pointer (by calling
shared_from_this()) will throw bad_weak_ptr. [Or in some older
versions, is undefined behaviour instead.]
Both of them result from misusing the types and both [now] have
well-defined misbehaviours that result from doing so. You get to decide
which misbehaviour you prefer. But both are also easily avoided by
using factories.