一个智能指针模板的实现及应用

本文介绍了一个智能指针模板类的实现,通过该模板可以安全地管理对象指针的生命周期并正确回收内存。同时提供了一个使用示例,展示如何创建智能指针并使用其成员函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

智能指针提供了一种安全的处理对象指针及正确的回收对象指针内存的方法,本文给出了一个智能指针模板类,并给出了一个简单的实例

  1. ////////////////////////////SmartPoint.h///////////////////////////////////
  2. #ifndefSMARTPOINT_H_
  3. #defineSMARTPOINT_H_
  4. template<classT>
  5. classmem_ptr
  6. {
  7. T*m_p;
  8. mem_ptr(T&);
  9. public:
  10. mem_ptr():m_p(0){}
  11. mem_ptr(T*p):m_p(p){}
  12. ~mem_ptr(){deletem_p;}
  13. inlineT&operator*()const{return*m_p;}
  14. inlineT*operator->()const{returnm_p;}
  15. inlineoperatorT*()const{returnm_p;}
  16. inlineconstmem_ptr<T>&operator=(T*p){set(p);return*this;}
  17. inlineT*set(T*p){deletem_p;m_p=p;returnm_p;}
  18. inlineT*get()const{returnm_p;}
  19. inlinevoidrelease(){m_p=0;}
  20. inlineboolempty()const{returnm_p==0;}
  21. };
  22. #endif
  23. ///////////////////////TestSmart.h///////////////////////////////////////
  24. #include<iostream>
  25. usingnamespacestd;
  26. classA
  27. {
  28. public:
  29. A(inta,intb):m_a(a),m_b(b)
  30. {
  31. }
  32. voidShow()
  33. {
  34. cout<<m_a<<endl;
  35. cout<<m_b<<endl;
  36. }
  37. private:
  38. intm_a;
  39. intm_b;
  40. };
  41. ///////////////////////////main.cpp///////////////////////////////////////
  42. #include"SmartPoint.h"
  43. #include"TestSmart.h"
  44. voidmain()
  45. {
  46. mem_ptr<A>m_A=newA(1,2);
  47. m_A->Show();
  48. //程序退出时调用m_A的析构函数释放对象A的内存
  49. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值