首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >C++核心准则ES.24: 使用unique_ptr<T>管理指针

C++核心准则ES.24: 使用unique_ptr<T>管理指针

作者头像
面向对象思考
发布2020-04-29 10:01:59
发布2020-04-29 10:01:59
49810
代码可运行
举报
运行总次数:0
代码可运行

ES.24: 使用unique_ptr<T>管理指针

Reason(原因)

Using std::unique_ptr is the simplest way to avoid leaks. It is reliable, it makes the type system do much of the work to validate ownership safety, it increases readability, and it has zero or near zero run-time cost.

使用std::unique_ptr是避免泄露的最简单方法。它可靠,它使类型系统做更多的工作以便安全地验证所有权,它可以增加可读性,它的没有(或接近没有)运行时代价。

Example(示例)

代码语言:javascript
代码运行次数:0
运行
复制
void use(bool leak)
{
    auto p1 = make_unique<int>(7);   // OK
    int* p2 = new int{7};            // bad: might leak
    // ... no assignment to p2 ...
    if (leak) return;
    // ... no assignment to p2 ...
    vector<int> v(7);
    v.at(7) = 0;                    // exception thrown
    // ...
}

If leak == true the object pointed to by p2 is leaked and the object pointed to by p1 is not. The same is the case when at() throws.

如果leak==true,p2指向的对象就会发生泄露,但p1指向的对象就不会。at()抛出异常时也一样。

Enforcement(实施建议)

Look for raw pointers that are targets of new, malloc(), or functions that may return such pointers.

寻找new,malloc的结果直接赋值个原始指针,或者函数返回这样的指针的情况。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es24-use-a-unique_ptrt-to-hold-pointers

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档