[STL] 스마트 포인터

스마트 포인터
C++에서 동적 메모리 할당과 누수를 관리하는 도구
소스코드
#include <iostream>
using namespace std;

class Point {
	int x;
	int y;
public:
	Point(int _x = 0, int _y = 0) : x(_x), y(_y) {}
	void print() const { cout << x << ',' << y << endl; }
};

class PointPtr {
	Point* ptr;
public:
	PointPtr(Point* p) :ptr(p) {}
	~PointPtr() {
		delete ptr;
	}

	Point* operator->() const {
		return ptr;
	}

	Point& operator*() const {
		return *ptr;
	}
};

void main() {
	Point* p1 = new Point(2, 3); //PointPtr은 스택 메모리에, Point는 힙 메모리에 적재됨!
	PointPtr p2 = new Point(5, 5);

	p1->print(); //p1->print() 호출  (*p1).print();과 동일하게 동작함
	p2->print(); //p2.operator()->print() 호출
	cout << endl;

	(*p1).print(); //(*p1).print()호출
	(*p2).print(); //p2.operator*().print() 호출

//여기를 벗어나면 스택 메모리에 있는 p1과 p2가 자동으로 소멸자를 부르고, 
//그로인해 PointPtr에 있는 point객체는 delete되며 결과적으로 PointPtr을 삭제하면 Point도 삭제되는 구조가됨.
//이게 스마트 포인터
}
코드 내용
P1은 Point *형으로 힙 메모리에 적재되고 new Porint(2,3)도 힙 메모리에 적재됨.
P2는 PointPtr형으로 스택메모리에 적재되고 new Point(5,5)는 힙 메모리에 적재됨.

P1->print()는 p1이 Point형이므로 직접적으로 불러옴
P2->print()는 PointPtr클래스의 ->를 불러와 P2에 있는 Point를 반환하여 print()메소드를 건너건너 불러옴.

(*p1).print는 ->와 동일하게 동작함
(*p2).print는 PointPtr클래스의 operator*() 오버로딩한 메소드를 불러서 위와 동일하게 건너건너 불러옴.

Main이 끝나면 스택 메모리에 있는 P2는 사라질테고 자동으로 소멸자를 호출하여 P2에 있는 new Point(5,5)를 해제시킨다. 그것이 스마트 포인터의 역할. 하지만 P1은 누수발생.
실행 결과