共享Ptr与普通Ptr:声明后的对象创建

Shared Ptr vs Normal Ptr: Object Creation After Declaration

本文关键字:Ptr 创建 声明 对象 共享      更新时间:2023-10-16

对于普通指针,我可以声明一个指针,然后将其设置为一个新对象,但是对于共享指针,我不能这样做。为什么?

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