Boost logo

Boost Users :

From: Andrew Holden (aholden_at_[hidden])
Date: 2008-04-24 19:38:14


Richard Damon [Richard_at_[hidden]] wrote:
> Lex,
>
> If you really want bla to point to fooInstance then you need to use
>
> bla.reset(&fooInstance)
>
> BUT there are several condition that need to be satisfied or
> you have just set a time bomb in your program.
>
> 1st, fooInstance needs to be on the heap, and created by new.
> Your example code has fooInstance being a non-heap object,
> either on the stack if the declaration was in a function, or
> a global. This will lead to undefined behavior as soon as bla
> no longer points to fooInstance, or when bla goes out of
> scope, as the shared_ptr will try to delete something which
> was not new'ed

I've had the op's situation myself. My solution to making a shared
pointer reference a static object is to define a function called
"NullDelete", then pass NullDelete as a second parameter to the shared
pointer. This prevents the shared pointer from attempting to delete a
statically allocated object. Do avoid letting a shared pointer
reference a stack object, as you can have dangling shared pointers when
the object goes out of scope. Sample code follows:

void NullDelete (void const *)
{
        //Intentionally blank
}

Option 1:
static Foo static_foo1;
boost::shared_ptr <Foo> bar1 (&static_foo1, &NullDelete);

Option 2:
static Foo static_foo2;
boost::shared_ptr <Foo> bar2;
Bar2 = boost::shared_ptr <Foo> (&static_foo2, &NullDelete);

Option 1:
static Foo static_foo3;
boost::shared_ptr <Foo> bar3;
Bar3.reset (&static_foo3, &NullDelete);


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