为现有变量创建一个 boost::shared_ptr

2021-12-24 00:00:00 c++ boost shared-ptr smart-pointers

我有一个现有的变量,例如

I have an existing variable, e.g.

int a = 3;

我现在如何创建一个 boost::shared_ptra?例如:

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 坏事会发生

如果由于某种原因一个函数需要 shared_ptr 而你只有一个堆栈变量,你最好这样做:

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

看这里:

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

相关文章