首页/文章/ 详情

软件开发—「C++开发技巧之---智能指针使用 」

9月前浏览177
在 C++ 中,智能指针是管理动态分配内存的重要工具,它们自动处理内存释放,有效防止内存泄漏。C++11 引入了三种主要智能指针:std::unique_ptrstd::shared_ptr和 std::weak_ptr。以下是详细使用方法:
     

std::unique_ptr(独占所有权)    


   

   

   

   
  • 特点:同一时间只能有一个 unique_ptr指向对象,不可复 制但可移动。

  • 适用场景:独占资源的场景(如工厂模式返回对象)。

  • 基本用法

    #include<memory>

    // 创建 unique_ptr
    std::unique_ptr<int> ptr1 = std::make_unique<int>(42);// C++14 推荐
    std::unique_ptr<int>ptr2(newint(100));// 传统方式

    // 访问对象
    *ptr1 =10;
    std::cout <<*ptr1;// 输出 10

    // 转移所有权(移动语义)
    std::unique_ptr<int> ptr3 = std::move(ptr1);// ptr1 变为 nullptr
  • 自定义删除器(如文件句柄):

    auto fileDeleter =[](FILE* f){if(f)fclose(f);};
    std::unique_ptr<FILE,decltype(fileDeleter)>filePtr(fopen("test.txt","r"), fileDeleter);
     

std::shared_ptr(共享所有权)    


   

   

   

   
  • 特点:多个指针共享同一对象,通过引用计数管理生命周期。

  • 适用场景:需要多个所有者共享资源的场景。

  • 基本用法

    // 创建 shared_ptr(推荐 make_shared)
    auto ptr1 = std::make_shared<int>(42);
    std::shared_ptr<int>ptr2(newint(100));// 不推荐(可能内存泄漏)

    // 复 制增加引用计数
    auto ptr3 = ptr1;// 引用计数 +1

    // 手动查看引用计数
    std::cout << ptr1.use_count();// 输出 2(ptr1 和 ptr3)
  • 自定义删除器

    auto deleter =[](int* p){delete p;};
    std::shared_ptr<int>ptr(newint(42), deleter);
  • 循环引用问题

    structNode{
        std::shared_ptr<Node> next;// 导致循环引用
    };
    auto a = std::make_shared<Node>();
    auto b = std::make_shared<Node>();
    a->next = b;
    b->next = a;// 内存泄漏!

    解决方案:使用 std::weak_ptr

     

std::weak_ptr(弱引用)    


   

   

   
  • 特点:不增加引用计数,避免循环引用。

  • 适用场景:打破 shared_ptr的循环依赖。

  • 基本用法

    structNode{
        std::weak_ptr<Node> next;// 弱引用解决循环问题
    };

    auto a = std::make_shared<Node>();
    auto b = std::make_shared<Node>();
    a->next = b;// weak_ptr 不增加引用计数
    b->next = a;

    // 访问 weak_ptr 需转为 shared_ptr
    if(auto sharedPtr = a->next.lock()){
    // 对象仍存在
    }else{
    // 对象已被销毁
    }
     

智能指针对比总结    


   

   

   

示例代码:综合使用

输出: 

Resource created 

Resource created Use count: 2 

Resource destroyed 

Resource destroyed

通过合理使用智能指针,可显著提升 C++ 代码的安全性和可维护性。


来源:IFD优飞迪
二次开发电子云计算数字孪生工厂
著作权归作者所有,欢迎分享,未经许可,不得转载
首次发布时间:2025-11-10
最近编辑:9月前
优飞迪科技
赋能新仿真,创优新设计
获赞 324粉丝 349文章 520课程 4
点赞
收藏
作者推荐
未登录
还没有评论
课程
培训
服务
行家
VIP会员 学习计划 福利任务
下载APP
联系我们
帮助与反馈