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


基础教程推荐
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 从 std::cin 读取密码 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01