【问题标题】:Cannot use unique_ptr inside a map in a vector?不能在矢量的地图内使用 unique_ptr?
【发布时间】:2020-05-28 18:51:19
【问题描述】:

我想在vector 中的map 中使用unique_ptr。但我收到一条错误消息。 我不确定为什么以及如何解决这个问题。
这是代码。

#include <memory>

int main(int argc, char** argv)
{
    std::vector<std::map<int, std::unique_ptr<std::string>>> outputContainers;
    std::map<int, std::unique_ptr<std::string>> outputContainer;
    outputContainer[0] = std::make_unique<std::string>("test");
    outputContainers.push_back(std::move(outputContainer));
}

这是一条错误消息。

Error C2280 'std::pair<const int,std::unique_ptr<std::string,std::default_delete<std::string>>>::pair(const std::pair<const int,std::unique_ptr<std::string,std::default_delete<std::string>>> &)': attempting to reference a deleted function test C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Tools\MSVC\14.24.28314\include\xmemory  671 

【问题讨论】:

  • It works for me,只要我添加其他必要的标题。
  • @DanielH 你能告诉我你安装哪个库以及你使用哪个版本的visual studio吗?
  • @DanielH 从视觉上看 G++ 和 CL.EXE 编译器是有区别的。
  • @rafix07 是的,我看到当我切换到那里的最新 MSVC 编译器时,它失败了。看起来它正在尝试调用复制构造函数而不是移动构造函数?我认为这是 MSVC 的一个问题,标准说它应该可以工作,但实际上并没有多大帮助。
  • @rafix07 使用 VS2015,对我来说效果很好。您对哪个版本有问题?

标签: c++11 std visual-studio-2019


【解决方案1】:

当一个vector需要重新分配时,如果the element's type is_nothrow_move_constructible,它可能会将元素移动到新的存储中;否则,它必须复制(因此,如果任何构造函数抛出异常,它可以恢复到原始状态)。

std::map 的移动构造函数is not required to be noexcept。一些实现可能会提供比标准要求更强的保证,并使其成为noexcept;其他人可能不会。

这两个事实的交互导致只移动类型的地图向量是不可移植的 - 它可以与某些实现一起编译,但不能与其他实现一起编译。

【讨论】:

    猜你喜欢
    • 2012-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多