2013-02-20 87 views
1

我已定義的類myClass,其數據成員中的一個被智能指針::地圖

std::map<int,data*> dataMap 

數據被定義爲

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

插入數據到數據圖是做如下:dataMap[key] = new data; 以下分配會導致一個問題:

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

我想用auto_ptr代替數據* .how我怎麼做? - 因爲在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正確的方法示例代碼

+0

您使用的是C++ 03還是C++ 11? – 2013-02-20 11:05:19

+2

不要使用'auto_ptr',如果你有權訪問C++ 11,可以使用'std :: unique_ptr'或'std :: shared_ptr',否則回退到使用'boost :: shared_ptr'。 – Nim 2013-02-20 11:05:32

回答

1

對於此錯誤:
error C2440: 'delete' : cannot convert from 'std::tr1::shared_ptr<_Ty>' to 'void *'
您不需要刪除shared_ptr的即時消息。 shared_ptr將使用引用計數器保存資源(new data),並在引用計數器爲0時自動將其刪除,這意味着該資源根本沒有被使用。詳情請參閱manual of shared_ptr

4

使用auto_ptr是一個壞主意(它被棄用),一般更糟糕,甚至更糟糕when combined with standard containers

不想更好的設計std::shared_ptrstd::unique_ptrdepending on your situation)和你的代碼將有一個例外的工作:您需要建立相應的智能指針類型試圖將其插入到容器中時,作爲智能指針不是從隱含constructible生指針。

1

std::auto_ptr在容器中使用並不安全,爲什麼它被棄用。如果有的話,使用std::shared_ptrboost::shared_ptr

如果合適且可用,您也可以使用std::unique_ptr,但它有點棘手。

1

可以在C++ 11請使用std::unique_ptr,如果你有一個獨特的所有權(即對象將永遠不會被共享,只有創建者可以再一次破壞它),也可以使用std::shared_ptr如果你有共同所有權。

如果您使用的是C++ 03,則可以使用boost::shared_ptrboost::unique_ptr代替。