You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用std::make_unique创建Node智能指针报错:调用隐式删除的拷贝构造函数

解决std::unique_ptr相关的Node类编译错误

原代码

#include <memory>

struct Node
{
    int val;
    std::unique_ptr<Node> next;

    Node(int value, std::unique_ptr<Node> nextNode) : val(value), next(std::move(nextNode)){};
};

int main()
{
    Node headNode = Node(1, nullptr);
    std::unique_ptr<Node> head = std::make_unique<Node>(headNode);

    return 0;
}

编译错误信息

error: call to implicitly-deleted copy constructor of 'Node'
    return unique_ptr<_Tp>(new _Tp(_VSTD::forward<_Args>(__args)...));
                               ^   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
note: in instantiation of function template specialization 'std::make_unique<Node, Node &>' requested here
    std::unique_ptr<Node> head = std::make_unique<Node>(headNode);
                                      ^
note: copy constructor of 'Node' is implicitly deleted because field 'next' has a deleted copy constructor
    std::unique_ptr<Node> next;
                          ^
note: copy constructor is implicitly deleted because 'unique_ptr<Node>' has a user-declared move constructor
  unique_ptr(unique_ptr&& __u) _NOEXCEPT

错误原因

  • std::unique_ptr是独占式智能指针,不支持拷贝操作,其拷贝构造函数被显式删除,仅支持移动语义。
  • Node类包含std::unique_ptr<Node>成员,因此编译器会自动删除Node的拷贝构造函数。
  • 代码中std::make_unique<Node>(headNode)尝试调用Node的拷贝构造函数创建新对象,触发了编译错误。

解决方案

以下是几种可行的修复方式:

方案1:直接用make_unique创建堆对象

无需先构造栈上的headNode,直接通过make_unique传入构造参数创建堆对象,这是最简洁的写法:

#include <memory>

struct Node
{
    int val;
    std::unique_ptr<Node> next;

    Node(int value, std::unique_ptr<Node> nextNode) : val(value), next(std::move(nextNode)){};
};

int main()
{
    std::unique_ptr<Node> head = std::make_unique<Node>(1, nullptr);

    return 0;
}

方案2:移动栈上的Node对象到智能指针

如果必须保留栈上的headNode,可以通过std::move将其所有权转移到堆中(注意:转移后栈上的headNode会处于有效但未定义的状态,后续不应再使用):

#include <memory>

struct Node
{
    int val;
    std::unique_ptr<Node> next;

    Node(int value, std::unique_ptr<Node> nextNode) : val(value), next(std::move(nextNode)){};
};

int main()
{
    Node headNode = Node(1, nullptr);
    std::unique_ptr<Node> head = std::make_unique<Node>(std::move(headNode));

    return 0;
}

方案3:手动实现Node的拷贝构造函数(不推荐)

如果确实需要支持拷贝操作,需手动实现Node的拷贝构造函数,对next指针进行深拷贝,但这会打破unique_ptr的独占语义,仅适用于特殊场景:

#include <memory>

struct Node
{
    int val;
    std::unique_ptr<Node> next;

    Node(int value, std::unique_ptr<Node> nextNode) : val(value), next(std::move(nextNode)){};

    // 手动实现拷贝构造,深拷贝next指针
    Node(const Node& other) : val(other.val) {
        if (other.next) {
            next = std::make_unique<Node>(*other.next);
        }
    }
};

int main()
{
    Node headNode = Node(1, nullptr);
    std::unique_ptr<Node> head = std::make_unique<Node>(headNode);

    return 0;
}

内容的提问来源于stack exchange,提问作者lian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 03:55:21