c++ - std::map 中的智能指针

标签 c++ dictionary smart-pointers assign auto-ptr

我定义了一个类 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_ptrstd::unique_ptr ( depending on your situation ),你的代码将工作,但有一个异常(exception):你需要构造正确的尝试将其插入容器时的智能指针类型,因为智能指针不能从原始指针隐式构造。

关于c++ - std::map 中的智能指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14978243/

相关文章:

C++11 智能指针和多态性

c++ - VS2008 中的 char[] 问题 - 为什么 strcat 附加到空数组的末尾?

c++ - 内联结构成员

c++ - vector 、迭代器和 std::find

python - 如何从字典中随机选择一个项目?

ruby-on-rails - 如何在 ActiveRecord 类方法中使用 'map' 方法?

python - 将列表追加到字典中

c++ - 将对象附加到智能指针 vector 的最佳方法?

c++ - 如何在 C++ 类中存储智能指针列表?

c++ - RcppParallel 中二次型的并行计算