您的位置 首页 > 腾讯云社区

C++核心准则ES.26: 不要将一个变量用于两个无关的用途---面向对象思考

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

---来自腾讯云社区的---面向对象思考

关于作者: 瞎采新闻

这里可以显示个人介绍!这里可以显示个人介绍!

热门文章

留言与评论(共有 0 条评论)
   
验证码: