Boost logo

Boost Users :

Subject: Re: [Boost-users] shared_ptr to stack-allocated object
From: Emil Dotchevski (emil_at_[hidden])
Date: 2008-12-04 19:22:04


On Thu, Dec 4, 2008 at 4:03 PM, Jason Cipriani <jason.cipriani_at_[hidden]> wrote:
> I'm refactoring parts of an existing application to use shared_ptrs
> instead of raw pointers. What is the best way to deal with code like
> this (please note in this situation passing a pointer to a
> stack-allocated object to function is acceptable and safe):
>
> void function (shared_ptr<Object> ptr) { ... }
>
> void function2 () {
> Object o;
> function(&o); // <--- need to change this
> }
>
> It seems I have two choices, I am not sure which is better, or if
> there are other common techniques. I can either use a no-op delete
> function:
>
> void noop (Object *) {}
>
> void function2 () {
> Object o;
> function(shared_ptr<Object>(&o, noop));
> }
>
> Or I can allocate it on the heap instead of the stack, and let
> shared_ptr deal with the cleanup (this seems to be the more convenient
> solution):
>
> void function2 () {
> shared_ptr<Object> o(new Object);
> function(o);
> }
>
> What's the normal practice here?

I'm not sure what's normal, but if your function isn't going to take
ownership of the object you're passing (which in this case it can't do
anyway since the object is allocated on the stack), it should take
Object &, not shared_ptr<Object>.

Even if it must take shared_ptr<Object> for some reason, it's better
to take shared_ptr<Object> const &, to avoid the refcount
increment/decrement (in general, I can't think of a reason to pass
shared_ptr by value.)

Emil Dotchevski
Reverge Studios, Inc.
http://www.revergestudios.com/reblog/index.php?n=ReCode


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net