1

我已经定义了一个类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 而不是 data*。我该怎么做? - 因为在 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 的正确方法

4

4 回答 4

4

一般来说,使用是一个坏主意(它已被弃用),当与标准容器结合使用时auto_ptr甚至更糟。

Prefer the better designed std::shared_ptr or std::unique_ptr (depending on your situation) and your code will work with one exception: You need to construct the correct smart pointer type when trying to insert it into the container, as the smart pointers are not implicitly constructible from raw pointers.

于 2013-02-20T11:05:52.703 回答
1

std::auto_ptr is not safe to be used in containers, that why it's been deprecated. Use std::shared_ptr or boost::shared_ptr if available.

You could also use std::unique_ptr if appropriate and available, but it is a bit trickier.

于 2013-02-20T11:06:29.363 回答
1

You can use either std::unique_ptr in C++11 if you have a unique ownership (ie, the object will never be shared and only the creator can destruct it again) or you can use std::shared_ptr if you will have shared ownership.

If you're using C++03 you can use boost::shared_ptr or boost::unique_ptr instead.

于 2013-02-20T11:07:00.717 回答
1

For this error:
error C2440: 'delete' : cannot convert from 'std::tr1::shared_ptr<_Ty>' to 'void *'
You don't need to delete an instant of shared_ptr. The shared_ptr would hold the resource (the new data) with a reference counter, and delete it automatically when the reference counter is 0, meaning that the resource was not used at all. See the manual of shared_ptr for detail

于 2013-02-20T12:05:04.017 回答