본문 바로가기

PROGRAMMING LANGUAGE/C++

스마트포인터

#include <iostream>
#include <algorithm>
using namespace std;

class Pos
{
private:
	int xpos, ypos;
public:
	Pos(int x = 0, int y = 0) : xpos(x), ypos(y) { cout << "Pos 객체 생성" << endl; }
	~Pos() { cout << "Pos 객체 소멸" << endl; }
	void SetPos(int x, int y) { xpos = x; ypos = y; }
	friend ostream& operator<<(ostream& os, const Pos& pos);
};

ostream& operator<<(ostream& os, const Pos& pos)
{
	os << '[' << pos.xpos << ", " << pos.ypos << ']' << endl;
	return os;
}

class SmartPtr  
{
private:
	Pos* posptr;
public:
	SmartPtr(Pos* ptr) : posptr(ptr) {}
	~SmartPtr() { delete posptr; }

	Pos& operator *() const { return *posptr; }
	Pos* operator ->() const { return posptr; }
};

int main()
{
	SmartPtr sp(new Pos(1, 2));
	sp->SetPos(10, 20);
	cout << *sp;
	return 0;

}