C++自定义智能指针

发布时间:2026/11/2 6:09:48
C++自定义智能指针 template class T class counted_ptr; // 智能指针引用计数类 template class T class Ref_Ptr { friend class counted_ptrT; private: T* m_pTtr; // 实际的指针 size_t counted_ptr; // 引用计数 Ref_Ptr(T* p); virtual ~Ref_Ptr(); }; template class T Ref_PtrT::Ref_Ptr(T* p) { m_pTtr p; counted_ptr 1; coutRef_Ptr() 构造函数调用!endl; } template class T Ref_PtrT::~Ref_Ptr() { if (m_pTtr) { cout~Ref_Ptr() 析构函数函数调用endl; delete m_pTtr; counted_ptr 0; } m_pTtr NULL; } // 智能指针对象 template class T class counted_ptr { private: Ref_PtrT* m_pRef; // 引用计数 public: counted_ptr(); counted_ptr(T* p); ~counted_ptr(); // 重载运算,将左对象引用计数-1,并判断是否delete;将右对象1; counted_ptrT operator (counted_ptr other); // 重载指针操作*,- T operator *(); T* operator -(); // 拷贝构造函数,引用计数1 counted_ptr(counted_ptrT other); }; template class T counted_ptrT::counted_ptr() { m_pRef NULL; } templateclass T counted_ptrT::counted_ptr(T* p) { m_pRef new Ref_PtrT(p); coutcounted_ptr(T* p) 构造函数调用endl; } template class T counted_ptrT::counted_ptr(counted_ptrT other) { this-m_pRef other.m_pRef; (m_pRef-counted_ptr); coutcounted_ptr( other) 拷贝构造函数被调用,当前引用计数 this-m_pRef-counted_ptrendl; } template class T counted_ptrT counted_ptrT::operator(counted_ptr other) { // 将右操作对象引用计数1 (other.m_pRef-counted_ptr); // 由于左操作对象指向了新对象,需要将操作数-1; // 同时也防止了自赋值的方式. // 首先要判断这个对象是否已经指向了其他对象,这个很重要!防止左指针对象为null的情况. if (this-m_pRef) { if (--(this-m_pRef-counted_ptr) 0) { delete this-m_pRef; } } this-m_pRef other.m_pRef; coutoperator 被调用,当前引用计数 this-m_pRef-counted_ptrendl; return *this; } template class T T counted_ptrT::operator *() { return *(m_pRef-m_pTtr); } template class T T* counted_ptrT::operator-() { return (m_pRef-m_pTtr); } template class T counted_ptrT::~counted_ptr() {cout~counted_ptr() 析构函数被调用endl; if ((--m_pRef-counted_ptr) 0) { cout删除endl; delete m_pRef; m_pRef NULL; } if (m_pRef) { cout当前引用计数: m_pRef-counted_ptrendl; } } int main() { counted_ptrint* pPtr NULL; { counted_ptrint g_ptr; { // 声明一个ptr1智能指针,并测试*运算符 counted_ptrint ptr1(new int(4)); counted_ptrint ptr2; cout *ptr1 *ptr1endl; // 将生存期小的ptr1赋值给生存期更大的g_ptr; ptr2 ptr1; system(pause); g_ptr ptr1; system(pause); } // new int(4)并没有销毁,因为引用计数还有1个 cout *g_ptr*g_ptr endl; system(pause); } system(pause); getchar(); return 0; }参考std::shared_ptr - cppreference.com创作不易小小的支持一下吧

关于本文作者

来自尧图内容编辑团队

尧图内容编辑团队 内容团队

尧图内容编辑团队

本文由尧图网络内容编辑团队执笔。团队由资深项目经理、前端工程师与设计师组成,所有内容均来自亲手交付的真实项目,先讲清问题、再给出可落地的解法。尧图深耕北京网站建设十年,服务过京华建材集团、智造科技等各行业客户,把一线经验沉淀为可复用的行业观察。

  • 十年建站经验,覆盖建材、制造、服务、文创等
  • 项目经理把关选题与事实准确性
  • 工程师与设计师联合撰写专业细节
  • 统一编辑规范,保证文风与排版一致
  • 每月复盘转化数据,迭代选题方向

延伸阅读

相关资讯与近期热门内容

深度阅读推荐

建站决策前值得细读的三篇

网站改版的5个关键决策
2024-08-12

网站改版的5个关键决策

什么时候该改版、改到什么程度、如何避免流量掉光,京华建材集团改版复盘给出答案。

获取专属建站方案

看完文章,把您的行业与预算告诉我们,免费获取一份量身定制的官网建设方案与报价。

立即免费咨询