设为首页 加入收藏

TOP

2011年计算机二级C++辅导实例编程(17)
2014-10-20 15:30:03 来源: 作者: 【 】 浏览:55
Tags:2011年 计算机 二级 辅导 实例 编程

  一个简单的智能指针实现


  学习这个代码有助于理解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


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇2011年计算机二级C++辅导实例编程.. 下一篇2011年计算机二级C++辅导实例编程..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: