C++ - unordered_map 中的 unique_ptr 会导致错误

标签 c++ unique-ptr unordered-map

我有一个程序给了我一个模糊的错误,所以我没有发布数百行代码,而是制作了这个简化版本:

#include <unordered_map>
#include <memory>
#include <utility>

struct s
{
    int height;
    std::unordered_map<std::string, std::unique_ptr<s>> children;
};

void InitWD(s &wd_ptr, int height, std::unordered_map<std::string, std::unique_ptr<s>> children) //Initialize a WindowData
{
    wd_ptr.children=children;
    wd_ptr.height=height;
}

int main()
{
  s test;
  test.height=1;
  test.children=std::unordered_map<std::string, std::unique_ptr<s>>();
  std::unique_ptr<s> ptr(new s);
  InitWD(*ptr, 2, std::unordered_map<std::string, std::unique_ptr<s>>());
  test.children.emplace("two", std::move(ptr));
}

错误(带有 C++11 的 GCC 4.8)与 unique_ptrunordered_map 相关,我相信:

error: use of deleted function 'constexpr std::pair<_T1, _T2>::pair(const std::pair<_T1, _T2>&) [with _T1 = const std::basic_string<char>; _T2 = std::unique_ptr<s>]'

也许代码中的某个地方正在复制unique_ptr?这是我能想到的唯一会导致这样的错误的事情。

感谢任何帮助!

最佳答案

错误在这里:

wd_ptr.children=children;

这会尝试将复制 childrenwd_ptr.children。您需要将其更改为:

wd_ptr.children = std::move(children);

不幸的是,gcc 和 clang 都无法生成实际告诉您哪一行代码错误的诊断。

关于C++ - unordered_map 中的 unique_ptr 会导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41970136/

相关文章:

c++ - 填充静态 unordered_map 局部变量

c++ - 需要在C++中将函数分配给变量

c++ - 使用索引 for 循环遍历 Unordered_map

c++ - COM : convert 'const GUID*' to const wchar_t*

c++ - OpenMP C++ 中的线程

c++ - vector<unique_ptr<myclass>> 元素之间的指针

c++ - 使用智能指针管理缓冲区

c++ - std::multimap 上的 emplace_hint 是否保留等效元素的相对顺序?

c++ - 流迭代器的用法?

c++ - unique_ptr 到对象数组,构造函数有不同的行为