C++中为什么不要定义无名局部变量

本篇内容主要讲解“C++中为什么不要定义无名局部变量”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“C++中为什么不要定义无名局部变量”吧!

ES.84:不要定义无名局部变量

Reason(原因)

There is no such thing. What looks to a human like a variable without a name is to the compiler a statement consisting of a temporary that immediately goes out of scope.

不存在这么做的理由。以人的角度来看是一个无名变量,但从编译器看起来就是一个马上会离开作用域的临时变量构成的语句。

Example, bad(反面示例)

void f()
{
   lock<mutex>{mx};   // Bad
   // ...
}

This declares an unnamed lock object that immediately goes out of scope at the point of the semicolon. This is not an uncommon mistake. In particular, this particular example can lead to hard-to find race conditions.

代码中定义了一个马上会离开以分号为界的作用域的无名锁。这不是一个特别的错误。通常,这个常见的例子会导致一个难以发现的竞争条件。

Note(注意)

Unnamed function arguments are fine.

无名的函数参数是没有问题的。

Enforcement(实施建议)

Flag statements that are just a temporary.

标记只是临时存在的语句。

到此,相信大家对“C++中为什么不要定义无名局部变量”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!