2012-07-30 3 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

+1

왜 직접 해보지 않으시겠습니까? – Zaffy

+4

Imo, 스마트 포인터 구현이 간단한 할당을 제대로 처리하지 못하면 ... 아주 스마트 포인터가 아닙니다. –

답변

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이 할당 될 때 감소합니다. 카운트가 0으로 내려 가자 마자 내부 오브젝트가 원래 포인터와 함께 파괴됩니다. 당신이 경우

:

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 물론

관련 문제