본문 바로가기

고급C,C++

auto_ptr 클래스

auto_ptr 객체를 생성하려면, auto_ptr 템플릿이 들어있는 memory 헤더파일을 포함시켜야 한다. 그러고 나서, 일반적인 템플릿 구문을 사용하여 필요한 포인터의 종류를 구체화한다.

auto_ptr<double> pd(new double); //double 을 지시하는 auto_ptr
//(double* 대신에 사용한다)
auto_ptr<string> ps(new string); //string을 지시하는 auto_ptr
//(string * 대신에 사용한다)



#include <memory>
void remodel(string & str)
{
auto_ptr<string> ps(new string(str));
...
if(weird_thing())
throw exception();
str = *ps;
//delete ps; 이행은 이제 필요없다.
return;
}


auto_ptr 생성자는 explicit 이다. 따라서 어떤 포인터로부터 auto_ptr 객체로 암시적 데이터형 변환이 허용되지 않는다.
auto_ptr<double> pd;
double * p_reg = new double;
pd = p_reg; //허용되지 않는다(암시적 변환)
pd = auto_ptr<double>(p_reg); //허용된다(명시적변환)
auto_ptr<double> pauto = p_reg;//허용되지 않는다(암시적 변환)
auto_ptr<double> pauto(p_reg);/허용된다(명시적변환)







auto_ptr 주의 사항
new [] 에 의해 할당되거나 단순히 변수를 선언하여 할당된 메모리가 아니라, new에 의해 할당된 메모리에만 auto_ptr 객체를 사용해야 한다.
auto_ptr<int> pi(new int[200]); //허용되지 않는다.

string vacation("나는 구름처럼 외롭게 방황했다.");
auto_ptr<string> pvac(&vacation); //허용되지 않는다.


하나의 스마트 포인터만이 특정 객체를 소유할 수 있또록 소유권 개념을 도입한다. 스마트 포인터가 그 객체를 소유하고 있는 경우에만, 파괴자가 그 객체를 삭제한다. 그러고 나서, 대입을 통해 소유권을 이전시킨다. 이 방법이 auto_ptr가 사용하는 전략이다.