【问题标题】:Compile error with initialization of an std::shared_ptr of type std::unordered_map初始化 std::unordered_map 类型的 std::shared_ptr 时编译错误
【发布时间】:2020-12-03 06:58:49
【问题描述】:

我是 C++ 智能指针的新手,在我的代码中的某个时刻,我需要一个 unordered_map 的共享指针。我意识到我无法通过以下方式初始化 shared_ptr:

    typedef std::unordered_map<std::string, std::string> JsonDict;

    std::shared_ptr<JsonDict> ret = std::make_shared<JsonDict>(new JsonDict);

这是我得到的编译错误:

*错误 C2664 'std::unordered_mapstd::string,std::string,std::hash<_kty>,std::allocator<:pair _kty> >>::unordered_map(const std::unordered_map<_kty>,std::equal_to<_ty>,std::allocator<:pair _kty>>> & )': 无法从 'std::unordered_mapstd::string,std::string,std::hash<_kty>,std::allocator<:pair _kty>> 转换参数 1 > ' 到 'const std::allocator<:pair _kty>> &' *

我真的不明白为什么会出现这个编译错误。

【问题讨论】:

  • make_shared() 采用构造函数参数。在您的情况下,只需执行 std::shared_ptr ret = std::make_shared();因为 JsonDict 是 unordered_map 并且 unorder_map 没有构造函数将指针指向另一个 unordered_map -> 你会得到编译器错误
  • 阅读docs点1):构造一个T类型的对象(...)

标签: c++ c++11 shared-ptr smart-pointers


【解决方案1】:

您不会自己分配对象,make_shared 会为您分配。它接受的参数用于构造对象本身,而不是指向它的指针。所以你的行应该读作

std::shared_ptr<JsonDict> ret = std::make_shared<JsonDict>();

(可以把它想象成“make_shared 是新的new”,尽管最常提到的是make_unique。)

【讨论】:

  • 是的,但我的问题是为什么会出现编译错误。我有一个工作代码,但我想知道为什么这条线不起作用。它应该进行双重分配并被编译不是吗?
  • @MahshidKhezriNejad 不,这是因为您正在尝试构造 std::unordered_map 的实例,并将指向其中的指针作为构造参数传递。例如,尝试JsonDict ret = new JsonDict;
【解决方案2】:

你的错误是试图分配自己的对象。所以你需要这样写:auto ret = std::make_shared&lt;JsonDict&gt;();std::shared_ptr&lt;JsonDict&gt; ret = std::make_shared&lt;JsonDict&gt;();

你得到错误的另一件事是因为你被减速 JsonDict 为std::unordered_map&lt;std::string, std::string&gt; 并且你试图插入一个: std::unordered_map&lt;std::string, std::string&gt; 而不是 &lt;std::string, std::string&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多