一个简单的智能指针实现
学习这个代码有助于理解shared_ptr指针的实现方法
smart.cpp
1 namespace smart
2 {
3 // 引用计数类.
4 class smart_count
5 {
6 public:
7 smart_count(int c = 0) : use_count(c) {}
8 ~smart_count() {}
9
10 // 增加引用计数, 并返回计数值.
11 int addref() { return ++use_count; }
12 // 减少引用计数, 并返回计数值.
13 int release() { return --use_count; }
14
15 private:
16 // 计数变量.
17 int use_count;
18 };
19
20 // 智能指针.
21 template
22 class smart_ptr
23 {
24 public:
25 // 构造指针, 并使引用计数置为1.
26 explicit smart_ptr (T* ptr) : p(ptr), u(new smart_count(1))
27 {}
28