스마트 포인터

Programming/C++ 2012. 10. 4. 13:16 |

스마트 포인터란 말 그대로 똑똑한 포인터이다. 스마트 포인터는 자기 스스로 하는 일이 존재하는 포인터이다.

스마트 포인터는 객체이다 포인터의 역할을 하는 객체를 뜻하는 것이다.


※ 프로그램의 개발을 목적으로 라이브러리에서 제공하는 스마트 포인터를 사용할 때 큰 도움이 될 것이다.


#include <iostream>

using namespace std;


class Point 

{

    private:

        int xpos, ypos;


    public:

        Point(int x=0, int y=0)

            :xpos(x), ypos(y)

        {

            cout<<"Point object created!!"<<endl;

        }


        ~Point()

        {

            cout<<"Point object cease to exist!!"<<endl;

        }

        

        void SetPos(int x, int y)

        {

            xpos = x;

            ypos = y;

        }


        friend ostream& operator<<(ostream& os, const Point& pos);

};


ostream& operator<<(ostream& os, const Point& pos)

{

    os<<pos.xpos<<", "<<pos.ypos<<endl;

    return os;

}


class SmartPtr        //기본적으로 여기 정의된 형태의 일을 포함해서 정의하게 되어있다.

{

    private:

        Point * posPtr;


    public:

        SmartPtr(Point * ptr)

            :posPtr(ptr)

        {   }


        Point& operator*() const

        {

            return *posPtr;

        }


        Point* operator->() const

        {

            return posPtr;

        }


        ~SmartPtr()

        {

            delete posPtr;

        }

};


int main(void)

{

    SmartPtr sptr1(new Point(1, 2));

    SmartPtr sptr2(new Point(2, 3));

    SmartPtr sptr3(new Point(3, 4));

    

    cout<<*sptr1;

    cout<<*sptr2;

    cout<<*sptr3;


    sptr1->SetPos(10, 20);

    sptr2->SetPos(20, 30);

    sptr3->SetPos(30, 40);


    cout<<*sptr1;

    cout<<*sptr2;

    cout<<*sptr3;


    return 0;

}


위의 예제에서 가장 중요한 사실은, Point 객체의 소멸을 위한 delete 연산이 자동으로 이뤄졌다는 사실이다.

그리고 바로 이것이 스마트 포인터의 똑똑함이다.

Posted by scii
: