[英]Creating shared_ptr from raw pointer
我有一個指向對象的指針。 我想將它存放在兩個擁有所有權的容器中。 所以我認為我很高興它成為C ++ 0x的shared_ptr。 我怎么能將原始指針轉換為shared_pointer?
typedef unordered_map<string, shared_ptr<classA>>MAP1;
MAP1 map1;
classA* obj = new classA();
map1[ID] = how could I store obj in map1??
謝謝
您需要確保不使用相同的原始指針初始化兩個shared_ptr對象,否則它將被刪除兩次。 做得更好(但仍然很糟糕)的方法:
classA* raw_ptr = new classA;
shared_ptr<classA> my_ptr(raw_ptr);
// or shared_ptr<classA> my_ptr = raw_ptr;
// ...
shared_ptr<classA> other_ptr(my_ptr);
// or shared_ptr<classA> other_ptr = my_ptr;
// WRONG: shared_ptr<classA> other_ptr(raw_ptr);
// ALSO WRONG: shared_ptr<classA> other_ptr = raw_ptr;
警告 :上面的代碼顯示不好的做法! raw_ptr
根本不應該作為變量存在。 如果直接使用new
的結果初始化智能指針,則可以降低意外初始化其他智能指針的風險。 你應該做的是:
shared_ptr<classA> my_ptr(new classA);
shared_ptr<classA> other_ptr(my_ptr);
有趣的是代碼也更簡潔。
編輯
我應該詳細說明它如何與地圖配合使用。 如果你有一個原始指針和兩個地圖,你可以做一些類似於我上面顯示的內容。
unordered_map<string, shared_ptr<classA> > my_map;
unordered_map<string, shared_ptr<classA> > that_guys_map;
shared_ptr<classA> my_ptr(new classA);
my_map.insert(make_pair("oi", my_ptr));
that_guys_map.insert(make_pair("oi", my_ptr));
// or my_map["oi"].reset(my_ptr);
// or my_map["oi"] = my_ptr;
// so many choices!
您可以使用多種方式,但reset()會很好:
map1[ID].reset(obj);
要解決兩個映射引用同一個shared_ptr的問題,我們可以:
map2[ID] = map1[ID];
請注意,避免雙重刪除的一般技巧是盡量避免使用原始指針。 因此避免:
classA* obj = new classA();
map1[ID].reset(obj);
而是將新的堆對象直接放入shared_ptr中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.