스마트 포인터


스마트 포인터는 동적으로 할당 (힙) 개체에 포인터를 저장하는 개체입니다. 그들은 많은과 같은 내장 C + + 포인터들이 자동으로 객체가 적절한 시간에 지적 삭제할 것을 제외하면 동작합니다. 그들은 동적으로 할당된 객체의 적절한 파괴를 위해 같은 스마트 포인터는 예외의 얼굴에 특히 유용합니다. 그들은 또한 여러 소유자가 공유 동적으로 할당된 객체를 추적하는 데 사용할 수 있습니다.

개념 스마트 포인터는 객체가 지적 소유로 볼 수 있으며, 그것이 더 이상 필요하지 않은 개체의 삭제에 대한 책임을 따라서.

스마트 포인터 라이브러리 여섯 스마트 포인터 클래스 템플릿을 제공합니다 :


scoped_ptr<boost/scoped_ptr.hpp>단일 개체의 단순 단독 소유. Noncopyable.
scoped_array<boost/scoped_array.hpp>배열의 간단한 단독 소유. Noncopyable.
shared_ptr<boost/shared_ptr.hpp>개체 소유권은 여러 포인터 사이에 공유.
shared_array<boost/shared_array.hpp>배열 소유권은 여러 포인터 사이에 공유.
weak_ptr<boost/weak_ptr.hpp>비 소유 shared_ptr가 소유한 개체의 관측합니다.
intrusive_ptr<boost/intrusive_ptr.hpp>임베디드 참조 카운트와 개체의 소유권을 공유.


 auto_ptr 템플릿 :이 템플릿은 표준을 보완하기 위해 고안되었습니다.

using namespace std;
class Stu
{
//*******************************************************originStu*************************************
class OriginStu
{
int num;
string name;
int rcnt;
public :
OriginStu(int _num,string _name)
{
num = _num;
name = _name;
rcnt = 1;
}
void AddRef()
{
rcnt++;
}
int Release()
{
rcnt--;
return rcnt;
}
};
//*******************************************************originStu*************************************
OriginStu *ostu;
public :
Stu(int _num,string _name)
{
ostu = new OriginStu(_num,_name);
}
Stu(const Stu &stu)
{
*this = stu;
ostu->AddRef();
}
~Stu()
{
if(ostu->Release()){
return;
}
delete ostu;
}
};


void main()
{
Stu s(2,"홍길동");
Stu s2(s);
}





///////////////////////////////////////////////////////


#include "stdafx.h"
using namespace std;

template<typename T>
class CountedPtr
{
private:
  
  struct Impl
  {
    T* p;
    size_t refs;

    Impl(T* pp) : p(pp), refs(1)  {}
    ~Impl()              { delete p; }
  };

  Impl* impl_;

public:
  explicit CountedPtr(T* p) : impl_( new Impl(p))    {}
  ~CountedPtr()                    { Decrement(); }
  CountedPtr(const CountedPtr& other) : impl_(other.impl_)    { Increment(); }
  CountedPtr& operator=(const CountedPtr& other)
  {
    if(impl_ != other.impl_)
    {
      Decrement();
      impl_ = oter.impl_;
      Increment();
    }
    return *this;
  }
  T* operator->() const
  {
    return impl_->p;
  }
  T& operator*() const
  {
    return *(impl_->p);
  }
private:
  void Decrement()
  {
    if( --(impl_->refs) ==0)
    {
      delete impl_;
    }
  }

  void Increment()
  {
    ++(impl_->refs);
  }
};

int main()
{
  int *a = new int[2];
  
  CountedPtr<int> intPtr(a);


  return 0;
}

[출처] 스마트



+ Recent posts