Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 views
in Technique[技术] by (71.8m points)

c++ - 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...