Search code examples
c++dictionarysmart-pointersassignauto-ptr

smart pointer in the std::map


I've defined a class myClass,one of its data members is

std::map<int,data*> dataMap

data is defined as

struct data
{
    int d1;
    int d2;
    std::string d3;
}

Inserting of data to the dataMap is done as follows :dataMap[key] = new data; the following assignment causes a problem:

myClass a1,a2;
//init a1;
a2 = a1;

I want to use auto_ptr for data instead of data*.how do i do that?- since there are a problem with destructing "bad pointers for data of a1" after a2 is destructed.std::map<int,std::auto_ptr<data> > is problematic to compile

Upd As you advised I use std::shared_ptr but it still causes a problems : in VS10

error C2440: 'delete' : cannot convert from 'std::tr1::shared_ptr<_Ty>' to 'void *'
1>          with
1>          [
1>              _Ty=data
1>          ]

Can you write sample code pointing the correct way to use shared_ptr


Solution

  • 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