ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

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
返回列表