Boost logo

Boost :

Subject: Re: [boost] Could shared_ptr cause memory leak?
From: hh h (jupiter.hce_at_[hidden])
Date: 2019-01-03 21:27:44


Thanks Josh, just wandering why the shared_ptr does not have a
dereference function? Looks the only way to break the reference loop
manually is calling b.reset() which might cause other implication, I
am going to use a raw pointer. Never use shared_from_this to its own
members.

On 1/4/19, Josh Juran via Boost <boost_at_[hidden]> wrote:
> On Jan 3, 2019, at 2:25 PM, hh h via Boost <boost_at_[hidden]> wrote:
>
>> Suppose I have a session object A, the shared_ptr<A> is created and
>> stored in a global connection list after a connection is accepted by
>> async_accept, when the connection is terminated, the reference in
>> connection list is removed, but since A has a member B still holds A
>> reference, that session object is never deleted, is it memory leak?
>>
>> class A : public boost::enable_shared_from_this<A> {
>> public:
>> A();
>> ~A();
>> void Start() {b = make_shared<B>(shared_from_this());}
>> void Stop();
>> private:
>> shared_ptr<B> b;
>> };
>
> Yes, what you describe is a resource leak due to a reference loop foiling
> shared_ptr's RAII reference counting.
>
> There are several ways to remedy this, one of which is to use a weak_ptr for
> one of the references. Higher-risk options include making sure to break the
> reference loop manually, or using a raw pointer instead.
>
> Josh
>
>
> _______________________________________________
> Unsubscribe & other changes:
> http://lists.boost.org/mailman/listinfo.cgi/boost
>


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk