template<typename T>
class Smart_Ptr {
public:
Smart_Ptr(T* s) : source(s){
cnt = new int(1);
}
Smart_Ptr(Smart_Ptr& p) {
source = p.source;
++(*p.cnt);
cnt = p.cnt;
}
~Smart_Ptr() {
destroy();
}
Smart_Ptr<T>& operator=(Smart_Ptr& p) {
++(*p.cnt); // must be in first line, avoid the situation " p = p"
destroy();
source = p.source;
cnt = p.cnt;
return *this;
}
T* operator->() {
return source;
}
T& operator*() {
return *source;
}
private:
T* source;
int* cnt;
void destroy() {
if (*cnt <= 1) {
delete source;
delete cnt;
}
--(*cnt);
}
};
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。