创建一个boost :: shared_ptr的到一个现有的变量 [英] Create a boost::shared_ptr to an existing variable
问题描述
我有一个现有的变量,例如
int类型的= 3;
如何我现在可以创建一个的boost :: shared_ptr的
到 A
?例如:
的boost :: shared_ptr的< INT> a_ptr =安培; A; //这不起作用
虽然你应该把变量到托管指针上的创作,从现有的指针做到这一点。
为int * A = INT新;
提高:: shared_ptr的< INT> a_ptr(一);
这就是说你最绝对不希望被放在堆栈变量为shared_ptr的不好的事情会发生
如果由于某种原因,函数将shared_ptr的,你只需要一个堆栈varaible你最好这样做:
int类型的= 9;
提高:: shared_ptr的< INT> a_ptr =的boost :: make_shared(一);
在这里看到:
<一个href=\"http://www.boost.org/doc/libs/1_43_0/libs/smart_ptr/make_shared.html\">http://www.boost.org/doc/libs/1_43_0/libs/smart_ptr/make_shared.html
也值得一提的是,shared_ptr的是在C ++ 11的标准,如果你能使用的。可以组合使用自动与make_shared像香草萨特在构建谈话指出。
的#include&LT;内存和GT;int类型的= 9;
汽车a_ptr =的std :: make_shared(9);
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
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);
这篇关于创建一个boost :: shared_ptr的到一个现有的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!