Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a boost::shared_ptr to an existing variable

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 
like image 446
Bill Cheatham Avatar asked Dec 11 '11 18:12

Bill Cheatham


People also ask

What is boost :: shared_ptr?

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.

What does shared_ptr get () do?

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.

What is a shared_ptr in C++?

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.

Can shared_ptr be copied?

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.


Video Answer


1 Answers

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); 

That said you most definitely do not want to be putting stack variables into shared_ptr BAD THINGS WILL HAPPEN

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); 
like image 113
111111 Avatar answered Oct 05 '22 00:10

111111