初始化类型为std :: unordered_map的std :: shared_ptr时发生编译错误

时间:2020-08-13 12:15:50

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

我是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 :: equal_to <_Kty>,std :: allocator >> :: unordered_map(const std :: unordered_map <_Kty,_Ty,std :: hash <_Kty>,std :: equal_to <_Ty>,std :: allocator >>& )': 无法从'std :: unordered_mapstd :: string,std :: string,std :: hash <_Kty,std :: equal_to <_Kty>,std :: allocator >转换参数1 >到 'const std :: allocator >&'*

我不太了解为什么会出现此编译错误。

2 个答案:

答案 0 :(得分:1)

您不必自己分配对象,make_shared会为您分配对象。它接受的参数用于构造对象本身,而不是指向它的指针。因此您的行应显示为

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

(尽管“ make_shared是最常见的new,但它被认为是新的make_unique”)。

答案 1 :(得分:1)

您的错误是试图分配自己的对象。因此,您需要这样写:auto ret = std::make_shared<JsonDict>();std::shared_ptr<JsonDict> ret = std::make_shared<JsonDict>();

导致错误的另一件事是因为您将JsonDict减速为std::unordered_map<std::string, std::string>,并且试图插入: std::unordered_map<std::string, std::string>代替<std::string, std::string>