C++核心准则R.20: 使用unique_ptr或者shared_ptr表示所有权

R.20: Use unique_ptr or shared_ptr to represent ownership

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

 

Reason(原因)

They can prevent resource leaks.

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

 

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"
}

This will leak the object used to initialize p1 (only).

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

 

Enforcement(实施建议)

(Simple) Warn if the return value of new or a function call with return value of pointer type is assigned to a raw pointer.

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

 

原文链接:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r20-use-unique_ptr-or-shared_ptr-to-represent-ownership


 

觉得本文有帮助?欢迎点赞并分享给更多的人。

阅读更多更新文章,请关注微信公众号【面向对象思考】

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章