【发布时间】: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