자료 저장소

# 스마트 포인터(Smart Pointer)

- 스마트 포인터는 객체이며, 자기 스스로 하는 일이 존재하는 포인터이다.

■ 간단한 스마트 포인터

class SmartPtr 
{
private:
Point * posptr;
public:
SmartPtr(Point * ptr) : posptr(ptr)
{ }

Point& operator*() const
{
return *posptr;
}
Point* operator->() const
{
return posptr;
}
~SmartPtr()
{
delete posptr;
}
};

위 클래스를 대상으로 객체를 생성하면 포인터와 같은 ->,* 연산자를 사용할 수 있다.
단순한 포인터이지만 메모리 해제를 하는 delete 연산이 자동으로 이루어지는것을 볼 수 있다.

스마트 포인터는 전문 개발자들이 개발한 이후에도 오랜시간 실무에 사용하면서 다듬어 가는 클래스이다.
그래서 보통 스마트포인터를 개인적으로 구현해 사용하는 경우는 드물며 오랜 시간 다듬어진, 그래서 라이브러리
일부로 포함되어 있는 스마트 포인터를 활용하는 경우가 대부분이다.


# 펑터(Functor)

- 함수처럼 동작하는 클래스를 가리켜(Functor)라고 하며 '함수 오브젝트(Funtion Object)'라고도 불린다.
#include <iostream> 
usingnamespacestd;

class Point
{
private:
int xpos, ypos;
public:
Point(int x=0, int y=0) : xpos(x), ypos(y)
{ }
Point operator+(const Point & pos) const
{
return Point(xpos+pos.xpos, ypos+pos.ypos);
}
friend ostream& operator<<(ostream& os, const Point& pos);
};

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

class Adder
{
public:
intoperator()(constint &n1, constint &n2)
{
return n1+n2;
}
doubleoperator()(constdouble &e1, constdouble &e2)
{
return e1+e2;
}
Point operator()(const Point &pos1, const Point &pos2)
{
return pos1+pos2;
}
};

int main(void)
{
Adder adder;
cout<<adder(1, 3)<<endl;
cout<<adder(1.5, 3.7)<<endl;
cout<<adder(Point(3, 4), Point(7, 9));
return0;
}
위 예제에서 정의한 Adder 클래스와 같이함수처럼 동작하는 클래스를 가리켜 '펑터(Functor)'라 한다.

책본문에서는 오름차순과 내림차순의 () 연산자를 오버로딩해서 전달하는 객체에 따라 오름차순과 내림차순으로
정렬되는 예제를 보여주고 있다. 펑터의 유용성에 대해 아직은 잘 모르지만 아무튼 유용해 보인다.
다른 책들을 보면서 조금씩 익혀가다보면 정말 유용하게 쓰일때가 있을듯 싶다.
댓글 로드 중…

최근에 게시된 글