2012-07-30 68 views
1

如果我使用=運算符爲它指定一個新的指針,以前的指針是否會自動在std :: shared_ptr中被銷燬(或取消引用)?在std :: shared_ptr中使用=運算符時以前的指針是否被銷燬?

例如:

std::shared_ptr<Type> sp1 (ptr1, std::ptr_fun(destroy)); 
std::shared_ptr<Type> sp2 (ptr2); 

sp1 = sp2; // now, will ptr1 be dereferenced and/or destroyed? 
// and will the destroy() function get called? 
+1

當然,否則會泄漏。 – GManNickG 2012-07-30 03:44:19

+1

你爲什麼不嘗試自己? – Zaffy 2012-07-30 03:52:22

+4

Imo,如果一個智能指針實現沒有正確處理簡單的賦值...它不是一個非常聰明的指針。 – 2012-07-30 04:07:00

回答

4

是的,否則你將有一個泄漏,它會破壞具有智能PTR的目的。

只是做了簡單的測試,我沒有得到任何泄漏

#define BOOST_TEST_MODULE leakTest 
#include <boost/test/unit_test.hpp> 


BOOST_AUTO_TEST_CASE(Leak_Test) 
{ 
    std::shared_ptr<int> sp1 (new int(3)); 
    std::shared_ptr<int> sp2 (new int(4)); 

    sp1 = sp2; 
} 

結果:

運行1個測試用例...

*未檢測到錯誤新聞任何關鍵要繼續。

。 。

2

是的,它的確如此。 shared_ptr是一個數據結構,它有一個實際上保持原始指針的內部對象。這個內部對象有一個計數器,在我們每次複製shared_ptr時遞增,當shared_ptr被銷燬或被分配另一個shared_ptr時遞減。一旦計數降到零,內部對象就會與原始指針一起被銷燬。

在你的情況:

std::shared_ptr<Type> sp1 (ptr1, std::ptr_fun(destroy)); //the counter of sp1 is 1 
std::shared_ptr<Type> sp2 (ptr2); //the counter of sp2 is 1 
sp1 = sp2; //the counter of sp1 is 0, the counter of sp2 is 2 

所以,PTR1將被銷燬,SP1和SP2將共享相同的指針PTR2

相關問題