共享Ptr与普通Ptr:声明后的对象创建
Shared Ptr vs Normal Ptr: Object Creation After Declaration
对于普通指针,我可以声明一个指针,然后将其设置为一个新对象,但是对于共享指针,我不能这样做。为什么?
#include <memory>
struct node{
int num;
node* next;
};
int main()
{
std::shared_ptr<node> new_node1 = NULL; // WORKS
new_node1 = new node; // ERROR, why?
node* new_node2 = NULL; //WORKS
new_node2 = new node; //WORKS
return 0;
}
为什么不能为共享指针创建一个新对象?有办法吗?
std::shared_ptr<node> n(new node);
n.reset(new node);
n = std::make_shared<node>();
您应该选择make_shared
这是因为在operator=()
调用期间调用的构造函数被标记为explicit
。
要解决这个问题:
new_node1 = std::shared_ptr<node>(new node);
或:
new_node1 = std::make_shared<node>();
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 使用std::multimap迭代器创建std::list
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 使用CMake创建QML插件
- 如何在c++中为模板函数实例创建快捷方式
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- OpenCV EqualizeHist()从彩色图像创建黑白图像
- 试图在visual studio上用C++创建一个桌面应用程序
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 如何在C++20中创建模板别名的推导指南
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 如何创建一个空的全局类并在启动时实例化它
- 无法创建抽象类的实例
- 从另一个唯一 ptr 的原始 ptr 创建唯一的 ptr
- 将 lamba 隐式转换为函数 ptr 以创建类
- 使用boost lambda构造创建初始化的智能ptr的容器
- 如何创建 std::string 包装器,它将 ptr 保留为 std::string 和 ptr 到创建该包装器实例的
- ptr<Node> a = 创建对象 < 节点 > ();
- 共享Ptr与普通Ptr:声明后的对象创建