use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique...

2025年11月25日 20:44 状态: processing

🚨 错误信息

In file included from /usr/include/c++/11/bits/stl_algobase.h:64, from /usr/include/c++/11/bits/stl_tree.h:63, from /usr/include/c++/11/map:60, from /data/gerrit/workspace_AIBox_repo/AICore/IC_NM_DataProvider/data_provider/src/graph/data/Node_Person.cpp:5: /usr/include/c++/11/bits/stl_pair.h:314:17: note: ‘constexpr std::pair<_T1, _T2>::pair(const std::pair<_T1, _T2>&) [with _T1 = const std::__cxx11::basic_string<char>; _T2 = std::unique_ptr<kuzu::common::Value>]’ is implicitly deleted because the default definition would be ill-formed: 314 | constexpr pair(const pair&) = default; ///< Copy constructor | ^~~~ /usr/include/c++/11/bits/stl_pair.h:314:17: error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = kuzu::common::Value; _Dp = std::default_delete<kuzu::common::Value>]’ In file included from /usr/include/c++/11/memory:76, from /data/gerrit/workspace_AIBox_repo/AICore/IC_NM_DataProvider/deps/linux-x86_64/kuzu/kuzu.hpp:38, from /data/gerrit/workspace_AIBox_repo/AICore/IC_NM_DataProvider/data_provider/include/private/graph/data/Node_Person.hpp:10, from /data/gerrit/workspace_AIBox_repo/AICore/IC_NM_DataProvider/data_provider/src/graph/data/Node_Person.cpp:13: /usr/include/c++/11/bits/unique_ptr.h:468:7: note: declared here 468 | unique_ptr(const unique_ptr&) = delete; | ^~~~~~~~~~

🤖 AI解决方案

报错分析报告

1. 错误翻译

原文:error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&)
译文:错误:使用了被删除的函数 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&)'

2. 原因分析

  • 根本原因:试图复制包含 std::unique_ptrstd::pair 对象
  • 错误位置:在 Node_Person.cpp 文件的第5行包含的map容器中
  • 具体分析
  • - std::unique_ptr 是独占所有权的智能指针,不可复制 - 代码中使用了 std::pair> 这样的结构 - 当尝试复制这个pair时,编译器隐式删除复制构造函数

    3. 解决方案

    方案一:使用移动语义(推荐)

    // 使用 std::move 转移所有权
    auto newPair = std::move(existingPair);
    
    // 或者在插入map时使用移动构造
    std::map<std::string, std::unique_ptr<kuzu::common::Value>> myMap;
    myMap.emplace(key, std::move(valuePtr));

    方案二:改用 std::shared_ptr

    // 如果确实需要共享所有权,改用 shared_ptr
    std::map<std::string, std::shared_ptr<kuzu::common::Value>> myMap;

    方案三:自定义pair的复制行为

    struct CustomPair {
        std::string key;
        std::unique_ptr<kuzu::common::Value> value;
        
        // 自定义移动构造函数
        CustomPair(CustomPair&& other) noexcept 
            : key(std::move(other.key)), value(std::move(other.value)) {}
        
        // 禁用复制构造函数
        CustomPair(const CustomPair&) = delete;
    };

    4. ️ 预防措施

    最佳实践

  • 优先使用移动语义:当处理不可复制的资源时,始终使用 std::move() 进行所有权转移
  • 使用emplace代替insert:对于map容器,使用 emplace() 方法可以避免不必要的复制操作
  • ️ 开发工具推荐

  • 静态分析工具:使用Clang静态分析器检测不可复制对象的误用
  • 编译器警告:开启 -Wdelete-non-virtual-dtor 等警告选项

---
请检查代码中对unique_ptr的操作,确保使用移动语义而非复制操作。