Create a boost::shared_ptr to an existing variable(为现有变量创建一个 boost::shared_ptr)
问题描述
我有一个现有的变量,例如
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 坏事会发生
如果由于某种原因一个函数需要 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);
这篇关于为现有变量创建一个 boost::shared_ptr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为现有变量创建一个 boost::shared_ptr


基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01