bit-pirate
bit-pirate

Reputation: 190

boost shared_ptr turns invalid on program exit

I ran into a problem with a dirty shutdown of my program, because of a shared pointer. I found a solution, but I'm not sure, if I have the right answer.

This is the minimalistic example:

double var;
boost::shared_ptr<const double> ptr1 (&var); // creates an invalid pointer on program exit
boost::shared_ptr<const double> ptr2 (new double); // works fine

int main (int argc, char **argv)
{
  return 0;
}

Here is my answer which I would like to varify:

In the case of ptr1 the pointed-to object will be deleted before the pointer, which then points to an invalid address. But in the case of ptr2 the "smartness" of the shared pointer handles the issue above. True?

Small extra question: Is there a way to make ptr1 work (I tried reset()) or is that bad programming practice (if so why)?

Thanks for the clarification!

Upvotes: 1

Views: 706

Answers (1)

jspcal
jspcal

Reputation: 51894

in the first case, the pointer isn't dynamically allocated, so the shared_ptr should not attempt to destroy the underlying object. that can be done by using a custom no-op deleter functor:

http://www.boost.org/doc/libs/1_51_0/libs/smart_ptr/sp_techniques.html#static

Upvotes: 4

Related Questions