Boost logo

Boost :

Subject: Re: [boost] Could shared_ptr cause memory leak?
From: Michael Caisse (mcaisse-lists_at_[hidden])
Date: 2019-01-04 00:16:13


Please do not top-post:
<https://www.boost.org/community/policy.html#quoting>

> On 1/4/19, Michael Caisse via Boost <boost_at_[hidden]> wrote:
>> On 1/3/19 11:25, hh h via Boost 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;
>>> };
>>>
>>
>> What are you trying to achieve with the above? The construct says B has
>> shared ownership of an A thing. Or do you want to 'use' an A thing?
>>
>
> On 1/3/19 15:35, hh h wrote:> Yes, B can access A functions
>

A shared_ptr denotes shared ownership. Don't use the shared pointer in B
if it is a usage pattern and not an ownership pattern. Pass a raw
pointer or reference instead. Also, does `b` have shared ownership in
the thing above? If not, it should be a unique_ptr.

-- 
Michael Caisse
Ciere Consulting
ciere.com

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