我是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
我不太了解为什么会出现此编译错误。
答案 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>
。