【发布时间】:2015-06-18 07:40:34
【问题描述】:
我有一个 auto_ptr 的地图,我只是想设置和获取地图元素,但它会产生编译器错误。我不明白编译器错误是什么意思,出了什么问题?
获取编译器错误:
[错误] 将 'const std::auto_ptr' 作为 'this' 参数传递 'std::auto_ptr<_tp>::operator std::auto_ptr_ref<_tp1>() [with _Tp1 = 诠释; _Tp = int]' 丢弃限定符 [-fpermissive]
设置编译器错误:
[错误] 'operator=' 不匹配(操作数类型为 'std::map, std::auto_ptr >::mapped_type {aka std::auto_ptr}' 和 'int*')
我还听说不建议在标准 c++ 库集合(列表、向量、地图)中使用 auto_ptr。在下面的代码中我应该使用什么样的智能指针?
std::map <std::string, std::auto_ptr<int> > myMap;
// Throws compiler error
std::auto_ptr <int> a = myMap["a"];
// Also throws compiler error
myMap["a"] = new int;
【问题讨论】:
-
使用
unique_ptr。auto_ptr将很快从 C++ 中删除。 -
@chris
unique_ptr在这里也不起作用(它已删除复制分配) -
@MattMcNabb,好点,你不能做第一个(第二个应该没问题)。那时,问题是您是要与地图共享所有权还是从地图中获取所有权。
-
@MattMcNabb:
unique_ptr可能是一个合理的选择,但std::auto_ptr <int> a = myMap["a"];应该更新为例如const std::auto_ptr<int>& a = myMap["a"];,类似地更改指针应该使用unique_ptrAPI:myMap["a"].reset(new int);。shared_ptr的另一种选择......
标签: c++ smart-pointers