C++核心准则ES.26: 不要将一个变量用于两个无关的用途

网友投稿 498 2022-10-13

C++核心准则ES.26: 不要将一个变量用于两个无关的用途

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​​

觉得本文有帮助?欢迎点赞并分享给更多的人。

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:FxBlog- 开源博客程序
下一篇:Mybatis中特殊SQL的执行
相关文章

 发表评论

暂时没有评论,来抢沙发吧~