前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则R.20: 使用unique_ptr或者shared_ptr表示所有权

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

作者头像
面向对象思考
发布2020-04-07 16:52:56
3160
发布2020-04-07 16:52:56
举报

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(考虑以下代码):

代码语言:javascript
复制
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


觉得本文有帮助?请分享给更多人。

关注【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-04-02,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • R.20: Use unique_ptr or shared_ptr to represent ownership
  • Reason(原因)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档