C++智能指针模板如何应用及其详细原理和操作步骤有哪些?

2026-04-12 11:190阅读0评论SEO问题
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计3116个文字,预计阅读时间需要13分钟。

C++智能指针模板如何应用及其详细原理和操作步骤有哪些?

目录 + 智能指针模板 + 使用智能指针 + 智能指针注意事项 + unique_ptr优于auto_ptr + 选择智能指针 + weak_ptr + 智能指针模板类 + void remodel(std::string str) { std::string *ps=new std::string(str); ... if(oh_no) { ... } }

目录
  • 智能指针模板类
  • 使用智能指针
  • 关于智能指针的注意事项
  • unique_ptr优于auto_ptr
  • 选择智能指针
  • weak_ptr

智能指针模板类

void remodel(std::string & str) { std::string *ps =new std::string(str); .... if(oh_no) throw exception(); ... delete ps; return; }

如果上面这段函数出现异常,那么就会发生内存泄漏。传统指针在执行动态内存分配时具有缺陷,很容易导致内存泄漏。如果有一个指针,指针被释放的同时,它指向的内存也能被释放,那就完美了。这种指针就是智能指针。

我们只介绍3个智能指针模板类:auto_ptrunique_ptrshared_ptr,顺便会提一下weak_ptr

阅读全文

本文共计3116个文字,预计阅读时间需要13分钟。

C++智能指针模板如何应用及其详细原理和操作步骤有哪些?

目录 + 智能指针模板 + 使用智能指针 + 智能指针注意事项 + unique_ptr优于auto_ptr + 选择智能指针 + weak_ptr + 智能指针模板类 + void remodel(std::string str) { std::string *ps=new std::string(str); ... if(oh_no) { ... } }

目录
  • 智能指针模板类
  • 使用智能指针
  • 关于智能指针的注意事项
  • unique_ptr优于auto_ptr
  • 选择智能指针
  • weak_ptr

智能指针模板类

void remodel(std::string & str) { std::string *ps =new std::string(str); .... if(oh_no) throw exception(); ... delete ps; return; }

如果上面这段函数出现异常,那么就会发生内存泄漏。传统指针在执行动态内存分配时具有缺陷,很容易导致内存泄漏。如果有一个指针,指针被释放的同时,它指向的内存也能被释放,那就完美了。这种指针就是智能指针。

我们只介绍3个智能指针模板类:auto_ptrunique_ptrshared_ptr,顺便会提一下weak_ptr

阅读全文