前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则:R.13: 在一个表达式中最多只执行一次显式资源分配

C++核心准则:R.13: 在一个表达式中最多只执行一次显式资源分配

作者头像
面向对象思考
发布2020-04-01 17:21:25
2740
发布2020-04-01 17:21:25
举报

R.13: Perform at most one explicit resource allocation in a single expression statement

R.13: 在一个表达式中最多只执行一次显式资源分配

Reason(原因)

If you perform two explicit resource allocations in one statement, you could leak resources because the order of evaluation of many subexpressions, including function arguments, is unspecified.

如果你在一个表达式中执行两次(或以上的)资源分配,由于包括函数参数在内的子表达式的执行顺序是没有定义的,因此可能导致资源泄露。

Example(示例)

代码语言:javascript
复制
void fun(shared_ptr<Widget> sp1, shared_ptr<Widget> sp2);

This fun can be called like this:

函数可能被这样调用:

代码语言:javascript
复制
// BAD: potential leak
fun(shared_ptr<Widget>(new Widget(a, b)), shared_ptr<Widget>(new Widget(c, d)));

This is exception-unsafe because the compiler may reorder the two expressions building the function's two arguments. In particular, the compiler can interleave execution of the two expressions: Memory allocation (by calling operator new) could be done first for both objects, followed by attempts to call the two Widget constructors. If one of the constructor calls throws an exception, then the other object's memory will never be released!

因为编译器可能会调整构建函数参数的两个表达式的执行顺序,这段代码在发生异常时会出问题。通常,编译器会交错执行两个表达式:(使用new进行)两个对象的内存分配可能首先进行,接下来调用两个Widget的构造函数。如果一个调用某个构造函数是抛出异常,那么另一个就永远不会被释放。

This subtle problem has a simple solution: Never perform more than one explicit resource allocation in a single expression statement. For example:

这个不易察觉的问题有一个简单的解决方案:永远不在一个表达式中执行两次(含两次)以上的显式资源分配。例如:

代码语言:javascript
复制
shared_ptr<Widget> sp1(new Widget(a, b)); // Better, but messy
fun(sp1, new Widget(c, d));

The best solution is to avoid explicit allocation entirely use factory functions that return owning objects:

最好的解决方案是使用返回管理对象的工厂方法彻底避免显式资源分配。

代码语言:javascript
复制
fun(make_shared<Widget>(a, b), make_shared<Widget>(c, d)); // Best

Write your own factory wrapper if there is not one already.

如果目前还不存在,那就自己写工厂包装类。

Enforcement(实施建议)

  • Flag expressions with multiple explicit resource allocations (problem: how many direct resource allocations can we recognize?)
  • 标记具有多个显式分配资源的表达式(问题是:我们可以识别出多少显式分配资源的情况?)

原文链接:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r13-perform-at-most-one-explicit-resource-allocation-in-a-single-expression-statement


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

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

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

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • R.13: Perform at most one explicit resource allocation in a single expression statement
  • Reason(原因)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档