I have an existing variable, e.g.
int a = 3;
How can I now create a boost::shared_ptr
to a
? For example:
boost::shared_ptr< int > a_ptr = &a; // this doesn't work
shared_ptr is now part of the C++11 Standard, as std::shared_ptr . Starting with Boost release 1.53, shared_ptr can be used to hold a pointer to a dynamically allocated array. This is accomplished by using an array type ( T[] or T[N] ) as the template parameter.
A shared_ptr may share ownership of an object while storing a pointer to another object. get() returns the stored pointer, not the managed pointer.
The shared_ptr type is a smart pointer in the C++ standard library that is designed for scenarios in which more than one owner might have to manage the lifetime of the object in memory.
The ownership of an object can only be shared with another shared_ptr by copy constructing or copy assigning its value to another shared_ptr . Constructing a new shared_ptr using the raw underlying pointer owned by another shared_ptr leads to undefined behavior.
although you should put the variable into a managed pointer on it's creation to do it from an existing pointer.
int *a=new int; boost::shared_ptr<int> a_ptr(a);
If for some reason a function takes shared_ptr and you only have a stack varaible you are better off doing this:
int a=9; boost::shared_ptr<int> a_ptr=boost::make_shared(a);
See here:
http://www.boost.org/doc/libs/1_43_0/libs/smart_ptr/make_shared.html
also it is worth noting that shared_ptr is in the c++11 standard if you are able using that. You can use auto in combination with make_shared like Herb Sutter notes in the build talk.
#include <memory> int a=9; auto a_ptr=std::make_shared(9);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With