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

I have some methods that reference this object, and some accept boost::shared_ptr . So far in my testing method, I have created shared_ptr pointing to one of these objects, and passed *ptr methods that are waiting for links. Is it possible to do it the other way around, for example. create a local object on the stack and then create a shared pointer to it in a safe way to get a direct alternative to the &obj operator with traditional pointers?

+6
source share
5 answers
 #include <boost/shared_ptr.hpp> void null_deleter(int *) {} int main() { int i = 0; boost::shared_ptr<int> p(&i, &null_deleter); } 
+10
source

If you think you need it, something is probably terribly wrong with your code.

If functions take a common pointer, this should be because they must extend the lifetime of the object. If they do not need to increase the lifetime of the object, they should take the link.

With what you do, they cannot extend the life of the facility. If they need and cannot, they can terminate access to an object that has gone out of scope through a copy of the shared pointer that you passed. Boom.

Perhaps this may make sense. They may need to extend their lifespan, but you will see that the object remains in effect longer than the longest that may be required to expand it. But I still highly recommend not doing this. It is incredibly fragile and makes all the code you call depends on how the calling code behaves.

+11
source

You can pass the corresponding debiter in the form constructor:

 template<class Y, class D> shared_ptr(Y * p, D d); 

The deleter object should not do anything in operator()() , for example, a function:

 template <typename T> void no_op(T*) {} 

with which you can build:

 boost::shared_ptr<Foo> f(&obj, no_op<Foo>); 
+6
source

You can use the lambda function of C ++ 11:

 boost::shared_ptr<Foo> f(&obj, \[ ](Foo*){}); 
0
source

You can pass null_deleter in the constructor.

 #include <boost/shared_ptr.hpp> #include <boost/core/null_deleter.hpp> int main() { int a = 0; boost::shared_ptr<int> pi(&a, boost::null_deleter()); } 

But look at this case: using an object after destruction:

 #include <boost/shared_ptr.hpp> #include <boost/core/null_deleter.hpp> class Y { public: void tryUse() { std::cout << "attempt to use :"<< (uintptr_t)(void*)this<< std::endl; } ~Y() { std::cout << "destructor: "<< (uintptr_t)(void*)this<< std::endl; } }; struct Y_user { boost::shared_ptr<Y> p; ~Y_user() { std::cout << "Y_user destructor: "<< (uintptr_t)(void*)this<< std::endl; if (p.get()) p->tryUse(); } }; int main() { { Y_user yu; Y y; boost::shared_ptr<Y> p (&y, boost::null_deleter() ); yu.p = p; } } 

will output the console as follows:

 destructor: 140737179995232 Y_user destructor: 140737179995264 attempt to use :140737179995232 
0
source

All Articles