Boost logo

Boost Users :

Subject: Re: [Boost-users] shared_ptr to stack-allocated object
From: Jeff Flinn (TriumphSprint2000_at_[hidden])
Date: 2008-12-05 08:11:18


Jason Cipriani 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);
> }

I do not see a need for any pointer usage in the above example code. I
see the following signatures for function depending on the inner details
of function.

void function (const Object& o) // original not to be modified
void function ( Object& o) // original to be modified
void function ( Object o) // original not to be modified

The latter for cheaply copy-able Object's.

I've come across lots of legacy C++ code that egregiously over uses the
heap when stack variables suffice. Typically from what was actually C
code merely made to compile with a C++ compiler. Or by developers coming
from languages where all variables are references of some sort.

If you do have a need to call 'function' and you have a pointer or
shared_ptr call function with a dereferenced pointer:

        function( *some_raw_or_shared_ptr );

Exceptions to the above would be if 'function' called some other
facility requiring the Object's lifetime to outlive function's scope. Or
if in fact the Object's existence affects the function's logic, that is
you branch based on the pointer being null.

Jeff


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