본문 바로가기
#DevStudy/C++

C++ 11 - 스마트 포인터

by 검은_백조 2016. 4. 8.

동적 메모리 할당과 해제에서 개발자의 실수로 발생하는 메모리 누수를 스마트하게 처리해주는 포인터.



1. auto_ptr


#include <memory>



class test{

public:

    test(){

        cout << "생성자" << endl;

    }

    ~test(){

        cout << "소멸자" << endl;

    }

};



int main(){

    auto_ptr<test> ptrtest(new test());

    

    return 0;

}


auto_ptr 에 의해 가리켜지는 주소는 오직 하나여야만 한다. (소유권을 갖는다.)

아래의 경우는 오류 발생.

    auto_ptr<test> ptrtest(new test(11));

    ptrtest->introduce();

    auto_ptr<test> ptrtest2 = ptrtest;

    ptrtest->introduce();

    ptrtest2->introduce();


*또한 auto_ptr 은 C++ 11 표준이 아니다.



2. unique_ptr

auto_ptr 의 소유권에 의한 오류를 컴파일 단계에서 잡아준다.

C++ 11 표준이다.



3. shared_ptr

하나의 동적 객체에 대해 아예 여러개의 스마트 포인터가 가리킬 수 있도록 한다.

C++ 11 표준이다.



'#DevStudy > C++' 카테고리의 다른 글

define 과 inline 함수  (0) 2016.08.09
C++ STL - 순차컨테이너  (0) 2016.04.19
C++ 11 - chrono 시간 측정  (0) 2016.04.06

댓글