尧图网络科技YAOTU DIGITAL 获取报价
获取报价
首页 / 资讯中心 / 文章详情

C++智能指针深入解析:unique_ptr、shared_ptr、weak_ptr全揭秘,面试必考的内存管理全解析

发布时间:2026/9/29 23:31:07

资讯中心
01
ARTICLE

C++智能指针深入解析:unique_ptr、shared_ptr、weak_ptr全揭秘,面试必考的内存管理全解析

C++智能指针深入解析:unique_ptr、shared_ptr、weak_ptr全揭秘,面试必考的内存管理全解析
C++智能指针深入解析:unique_ptr、shared_ptr、weak_ptr全揭秘,面试必考的内存管理全解析引言智能指针是C++11引入的革命性特性,也是大厂面试的高频考点。它让C++的内存管理变得安全、简单。本文将从RAII原理出发,深入讲解三种智能指针的使用场景、实现原理和最佳实践,帮你彻底掌握这个核心特性。一、智能指针基础1.1 为什么需要智能指针问题传统指针智能指针内存泄漏忘记delete自动释放异常安全异常时可能泄漏RAII保证释放所有权不明确明确语义悬空指针容易发生可避免1.2 RAII原理#includeiostream#includememory// 传统方式:容易忘记deletevoidtraditionalWay(){int*ptr=newint(42);// ... 可能因为异常或提前返回而忘记deletedeleteptr;// 容易忘记}// 智能指针方式:自动管理voidsmartPointerWay(){std::unique_ptrintptr=std::make_uniqueint(42);// 函数结束时自动释放,即使发生异常}intmain(){smartPointerWay();return0;}二、unique_ptr:独占所有权2.1 基本用法#includeiostream#includememory#includestringclassResource{public:Resource(conststd::stringname):name_(name){std::cout"Resource "name_" created"std::endl;}~Resource(){std::cout"Resource "name_" destroyed"std::endl;}voiduse(){std::cout"Using "name_std::endl;}private:std::string name_;};intmain(){// 创建unique_ptrstd::unique_ptrResourceres1=std::make_uniqueResource("A");res1-use();// 不能复制,只能移动// std::unique_ptrResource res2 = res1; // 编译错误std::unique_ptrResourceres2=std::move(res1);// 转移所有权// res1现在为空if(!res1)std::cout"res1 is null"std::endl;res2-use();return0;}2.2 自定义删除器#includeiostream#includememory#includefstream// 自定义删除器:关闭文件structFileDeleter{voidoperator()(FILE*fp)const{if(fp){fclose(fp);std::cout"File closed"std::endl;}}};intmain(){// 使用自定义删除器std::unique_ptrFILE,FileDeleterfile(fopen("test.txt","w"));if(file
02
RELATED NEWS

相关资讯

更多网站建设与数字化升级内容

03
WHY YAOTU

想打造同款高转化官网?

懂行业、懂生意,从建站到增长一站式陪跑

◈

场景化定制

不做模板站,围绕你的业务场景量身设计,小众不撞款。

◐

营销型架构

以转化目标组织内容与路径,让官网真正带来询盘。

▲

全周期服务

设计、开发、运营、运维一体,上线只是开始。

免费获取你的建站方案

留下需求,专属顾问 24 小时内为你输出方案建议。