참조 카운트에서 고전적입니다. 일부 기본 코드는 다음과 같이 보일 것입니다 (내가 생성 할 수있는 가장 짧은 코드). 참조 계산에 대해 모르는 경우가 아니면 간단해야합니다.
template <class CL>
struct refCount {
refCount() : nlinks_(1) , p_(0) {}
refCount(CL*p) : nlinks_(1) , p_(p) {}
~refCount() { if (!nlinks_) delete p_;}
size_t nlinks_;
CL* p_;
};
template <class CL>
class mySmartPtr {
public:
mySmartPtr() : rc_(new refCount<CL>()) {}
mySmartPtr(CL* p) : rc_(new refCount<CL>(p)) {}
mySmartPtr(const mySmartPtr<CL> & otherSmartPtr) : rc_(otherSmartPtr.rc_) { rc_->nlinks_++ ;}
mySmartPtr & operator=(const mySmartPtr<CL> & otherSmartPtr) {
otherSmartPtr.rc_->nlinks_++;
if (!(-- rc_->nlinks_)) delete rc_;
rc_ = otherSmartPtr.rc_;
return *this;}
CL& operator *() {return * rc_->p_ ; }
~mySmartPtr() { if(!(--rc_->nlinks_)) delete rc_;}
// commented to print #links (remove it)
// protected:
refCount<CL> *rc_;
};
동적/정적 캐스팅 (스레드 안전성)이 필요한 경우 약간의 작업이 더 필요합니다. 사용
예 :
그냥 관심 밖으로
int main()
{
mySmartPtr<int> i;
i = mySmartPtr<int>(new int(1));
*i = 7;
mySmartPtr<int> j(new int(3));
j = i;
std::cout << *j << std::endl ; // prints 7
std::cout << i.rc_->nlinks_ << std::endl ; // prints 2, i and j point to the same
{
mySmartPtr<int> k(j);
std::cout << i.rc_->nlinks_ << std::endl ; // prints 3, k points there two
}
std::cout << i.rc_->nlinks_ << std::endl ; // prints 2 , k gone out of scope
return 0;
}
, 왜 당신은 표준 라이브러리를 사용할 수 없습니다. 이것이 언제 요구 사항이 될지 궁금하다. – flipchart
부스트 또는 표준 라이브러리와 독립적이되고 싶습니까? 표준 라이브러리가 없으면 더 이상 C++이 아닙니다. – juanchopanza
나는 그 질문을 이해하지 못한다. std를 사용할 수 없거나 부스트를 사용할 수 없습니까? 아니면 둘 다 사용할 수 있습니까? – ronag