Boost logo

Boost :

Subject: Re: [boost] [smart_ptr] Interest in the missing smart pointer (that can target the stack)
From: Emil Dotchevski (emildotchevski_at_[hidden])
Date: 2016-01-30 22:29:50


On Sat, Jan 30, 2016 at 1:12 PM, Noah <duneroadrunner_at_[hidden]> wrote:

> Wow, shared_ptr really is quite an impressive little data type. But are
> you guys suggesting that it's already an adequate "smart pointer to stack
> objects" solution?

Some problems don't have a solution, you have to pick the right compromise.
The use of shared_ptr has the advantage of enabling the use of weak_ptr and
of interfaces that are expressed in terms of shared_ptr and don't care what
deleter was used with each instance. The disadvantage is that it could lead
to programmer errors, though the assert in my example should detect them.

> So I have a couple of questions about shared_ptr's implementation. Would
> doing the "shared_ptr to stack object" thing still involve a refcount
> object being allocated on the heap? In which case, you would lose a lot of
> the (potential) performance benefit of putting the object on the stack in
> the first place. Right?
>

With some extra acrobatic moves you can use an allocator (once you have
solid evidence from your profiler that this particular heap allocation
creates performance problems, though I'd bet the lunch money that in
practice that won't ever happen.)

> And also, how does make_shared<> combine the target object and refcount
> object into a single allocation? My current implementation of
> registered_ptr does it by just deriving a new object that contains both the
> target object (as the (public) base class) and the "management" object.
> This method is nice and simple, but it requires that the target type be
> able to act as a base class.

How it's done is unspecified :) but do note that shared_ptr goes beyond not
requiring the target type to be able to act as a base class, it even works
with void, e.g. this is valid C++:

shared_ptr<void> p(new my_type); //When the last reference expires,
~my_type will be called.

Emil


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