Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create a boost::shared_ptr to a local variable?

I have some methods that take a reference to a given object, and some are taking boost::shared_ptr. So far in my test method I created a shared_ptr pointing to one of these objects and pass *ptr to the methods expecting a reference. Is it possible to do it the other way round, e.g. create a local object on the stack, and then create a shared pointer to it in a safe way, to arrive at the straightforward alternative to &obj operator with traditional pointers?

like image 865
Grzenio Avatar asked Feb 12 '13 10:02

Grzenio


2 Answers

If you find you need this, something is probably horribly wrong with your code.

If the functions take a shared pointer, it should be because they need to extend the lifetime of the object. If they don't need to extend the lifetime of the object, they should take a reference.

With what you're doing, they can't extend the lifetime of the object. If they need to, and can't, they may wind up accessing an object that has gone out of scope through a copy of the shared pointer you passed them. Boom.

It's slightly possible this might make sense. It may be that they need to extend the lifespan but you will make sure that the object remains valid longer than the longest they might possibly need to extend it. But I'd still strongly suggest not doing this. It's incredibly fragile and makes all the code you call dependent on exactly how the calling code behaves.

like image 182
David Schwartz Avatar answered Sep 21 '22 20:09

David Schwartz


#include <boost/shared_ptr.hpp>

void null_deleter(int *)
{}

int main()
{
    int i = 0;
    boost::shared_ptr<int> p(&i, &null_deleter);
}
like image 22
Igor R. Avatar answered Sep 17 '22 20:09

Igor R.