C++中使用unique_ptr或者shared_ptr有什么作用

本篇内容主要讲解“C++中使用unique_ptr或者shared_ptr有什么作用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“C++中使用unique_ptr或者shared_ptr有什么作用”吧!

C.149:使用unique_ptr或者shared_ptr避免忘记销毁使用new创建的对象

Reason(原因)

避免资源泄露。

Example(示例)
void use(int i)
{
   auto p = new int {7};           // bad: initialize local pointers with new
   auto q = make_unique<int>(9);   // ok: guarantee the release of the memory-allocated for 9
   if (0 < i) return;              // maybe return and leak
   delete p;                       // too late
}
Enforcement(实施建议)
  • 提示使用new的结果初始化裸指针的情况。

  • 标记销毁局部变量的情况。

到此,相信大家对“C++中使用unique_ptr或者shared_ptr有什么作用”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!