闲着没事写了个智能指针
#include <iostream>
class SmartCount {
public:
explicit SmartCount(int count) : count_(0) {
count_ = count;
}
private:
explicit SmartCount(const SmartCount&);
SmartCount& operator = (const SmartCount&);
public:
int AddCount() {return ++count_;}
int Release() {return --count_;}
private:
int count_;
};
template<class T>
class SmartPtr {
public:
SmartPtr(T* ptr):ptr_(ptr),counter_(new SmartCount(1)) {
}
~SmartPtr() {
if (ptr_ && counter_->Release() <= 0) {
delete ptr_;
ptr_ = NULL;
delete counter_;
counter_ = NULL;
}
}
public:
SmartPtr(const SmartPtr<T>& smart_ptr) {
ptr_ = smart_ptr.ptr_;
counter_ = smart_ptr.counter_;
if (counter_) {
counter_->AddCount();
}
}
SmartPtr& operator = (const SmartPtr<T>& smart_ptr) {
if (&smart_ptr == this) {
return *this;
}
if (smart_ptr.counter_) {
smart_ptr.counter_->AddCount();
}
T* ptr_temp = ptr_;
SmartCount* count_temp = counter_;
ptr_ = smart_ptr.ptr_;
counter_ = smart_ptr.counter_;
if (ptr_temp && count_temp->Release() <= 0) {
delete ptr_temp;
ptr_temp = NULL;
delete count_temp;
count_temp = NULL;
}
return *this;
}
T* operator -> (void) {
return ptr_;
}
T& operator * (void) {
return *ptr_;
}
private:
T* ptr_;
SmartCount* counter_;
};
#include "main.h"
using namespace std;
class Test {
public:
Test(char* ch) {ch_ = ch;}
~Test() { }
void Print() {
cout << ch_ << endl;
cout << "333333" << endl;
}
private:
char* ch_;
};
int main(int argc, char* argv[]) {
SmartPtr<Test> p ( new Test("123"));
p->Print();
SmartPtr<Test> p2(new Test("333"));
p2 = p;
p2->Print();
SmartPtr<Test> p3(p2);
p3->Print();
}
骑虎100 一个有趣的网站 好玩的网站 http://www.qihu100.com