我有一个现有的变量,例如
I have an existing variable, e.g.
int a = 3;
我现在如何创建一个 boost::shared_ptr
到 a
?例如:
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);
如果由于某种原因一个函数需要 shared_ptr 而你只有一个堆栈变量,你最好这样做:
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);
看这里:
http://www.boost.org/doc/libs/1_43_0/libs/smart_ptr/make_shared.html
另外值得注意的是,如果您能够使用 shared_ptr,那么它在 c++11 标准中.您可以将 auto 与 make_shared 结合使用,就像构建演讲中的 Herb Sutter 笔记一样.
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!