std::unordered_map 插入错误shared_ptr C++
std::unordered_map insert error shared_ptr c++
我是第一次使用 std::unordered_map,但在插入我创建的地图时遇到问题。
A 类标头:
Class ClassA
{
public:
void func();
private:
std::unordered_map<std::string, std::shared_ptr<ClassB>> map;
}
A类CPP:
void ClassA::func()
{
map = std::unordered_map<std::string, std::shared_ptr<ClassB>>();
map.insert("string", std::make_shared<ClassB>());
}
我收到错误 c2664 std::_List_iterator<_Mylist> std::_Hash<_Traits>:::insert(std::_List_const_iterator<_Mylist>,std::p air<_Ty1,_Ty2> &&)' :无法将参数 1 从"常量字符 [17]"转换为"std::_List_const_iterator<_Mylist>"
有什么想法吗?
问题不在于shared_ptr
,而在于string
键。 显式实例化将解决此问题。 您还需要插入一个由键和值组成的pair
,而不是分别插入键和值:
map.insert(std::make_pair (std::string("string"), std::make_shared<ClassB>()));
另请参阅此相关答案,以获取更新颖、更复杂的解决方案。
>initializer_list也可以解决您的问题。
map.insert( {"string", std::make_shared<ClassB>()} );
相关文章:
- CLANG 编译器 说:变量"PTR"可能未初始化
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- 将 ptr 传递给 ptr 到 A 作为参数传递给 A 的函数是不好的做法吗?
- 为共享 ptr 向量实现复制 c'tor?
- 字符和整数中 **(ptr+1) 的值差异
- C++:在不中断共享的情况下通过引用传递共享 PTR?
- 如何将派生类从基 ptr 分配给 nlohmann::json
- 引用 std::shared:ptr 以避免引用计数
- 为什么我不能在不进行任何转换的情况下将浮点数放入任何类型的 ptr 中?
- 在调用函数时,ptr** 和 ptr*& 之间是否有区别,或者首选C++?
- 另一种类型的智能ptr,比如具有弱refs的unique_ptr
- 尝试打印出 *ptr++ 的值,以了解它是如何工作的
- 如何控制共享 ptr 引用计数?
- dopen():不以 root 身份运行时"failed to map segment from shared object"
- C++中的指针否定 (!ptr == NULL)
- 从const ptr*转换为ptr*时出现问题
- 无法使用 libtool 将 -shared 参数传递给 g++
- boost::shared_ptr和std::shared-ptr的同居
- 我可以用std::shared_ptr而不是boost::shared-ptr构建boost库吗
- shared-ptr-C++shared_ptr与unique_ptr用于资源管理