我定义了一个类 myClass
,它的一个数据成员是
std::map<int,data*> dataMap
数据定义为
struct data
{
int d1;
int d2;
std::string d3;
}
将数据插入 dataMap 的操作如下:dataMap[key] = new data;
以下分配会导致问题:
myClass a1,a2;
//init a1;
a2 = a1;
我想对数据使用 auto_ptr 而不是数据*。我该怎么做?-
因为在销毁 a2 之后销毁“a1 数据的错误指针”存在问题。 std::map<int,std::auto_ptr<data> >
编译有问题
Upd 正如您建议的那样,我使用 std::shared_ptr 但它仍然会导致问题:
在 VS10
error C2440: 'delete' : cannot convert from 'std::tr1::shared_ptr<_Ty>' to 'void *'
1> with
1> [
1> _Ty=data
1> ]
你能写出示例代码来指出正确使用 shared_ptr 的方法吗
最佳答案
使用 auto_ptr
通常是一个坏主意(已弃用),甚至更糟 when combined with standard containers .
首选设计更好的 std::shared_ptr
或 std::unique_ptr
( depending on your situation ),你的代码将工作,但有一个异常(exception):你需要构造正确的尝试将其插入容器时的智能指针类型,因为智能指针不能从原始指针隐式构造。
关于c++ - std::map 中的智能指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14978243/