C++怎么使用unique_ptr或者shared_ptr表示所有权

本篇内容介绍了“C++怎么使用unique_ptr或者shared_ptr表示所有权”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

R.20: 使用unique_ptr或者shared_ptr表示所有权

Reason(原因)

使用它们可以防止资源泄露。

Example(示例)

Consider(考虑以下代码):

void f()
{
   X x;
   X* p1 { new X };              // see also ???
   unique_ptr<T> p2 { new X };   // unique ownership; see also ???
   shared_ptr<T> p3 { new X };   // shared ownership; see also ???
   auto p4 = make_unique<X>();   // unique_ownership, preferable to the explicit use "new"
   auto p5 = make_shared<X>();   // shared ownership, preferable to the explicit use "new"
}

这段代码中(只有)用来初始化p1的对象会发生泄露。

Enforcement(实施建议)

(简单)如果new操作的返回值或者返回指针类型的函数调用的返回值被赋值给一个原始指针,发出警告。

“C++怎么使用unique_ptr或者shared_ptr表示所有权”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注网站,小编将为大家输出更多高质量的实用文章!