C++核心准则ES.26: 不要将一个变量用于两个无关的用途
面向对象思考
共 1265字,需浏览 3分钟
·
2020-04-29 23:21
ES.26: Don't use a variable for two unrelated purposes
ES.26: 不要将一个变量用于两个无关的用途
Reason(原因)
Readability and safety.
可读性和安全性。
Example, bad(反面示例)
void use()
{
int i;
for (i = 0; i < 20; ++i) { /* ... */ }
for (i = 0; i < 200; ++i) { /* ... */ } // bad: i recycled
}
Note(注意)
As an optimization, you may want to reuse a buffer as a scratch pad, but even then prefer to limit the variable's scope as much as possible and be careful not to cause bugs from data left in a recycled buffer as this is a common source of security bugs.
作为一种优化,你可能将buffer用作告诉暂存区,即使是这种用情况最好还是尽可能限定变量的作用域,而且注意不要因为留在循环使用的buffer中的数据引发错误。这是安全错误的一个常见来源。
void write_to_file() {
std::string buffer; // to avoid reallocations on every loop iteration
for (auto& o : objects)
{
// First part of the work.
generate_first_string(buffer, o);
write_to_file(buffer);
// Second part of the work.
generate_second_string(buffer, o);
write_to_file(buffer);
// etc...
}
}
Enforcement(实施建议)
Flag recycled variables.
标记循环使用的变量。
原文链接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es26-dont-use-a-variable-for-two-unrelated-purposes
觉得本文有帮助?请分享给更多人。
关注微信公众号【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!
评论