古典的參考計數。一些基本代碼看起來像這樣(我設法生成的最短代碼)。除非你對引用計數一無所知,否則應該是直截了當的。
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;
}
只是出於興趣,爲什麼你不能使用std庫。我很想知道這是什麼時候的需求 – flipchart
你想獨立於boost還是標準庫?沒有標準庫,它不再是真正的C++。 – juanchopanza
我不明白這個問題。你不能使用std或者你不能使用boost,或者兩者兼有? – ronag