C++核心準(zhǔn)則ES.26: 不要將一個(gè)變量用于兩個(gè)無關(guān)的用途

ES.26: Don't use a variable for two unrelated purposes
ES.26: 不要將一個(gè)變量用于兩個(gè)無關(guān)的用途
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.
作為一種優(yōu)化,你可能將buffer用作告訴暫存區(qū),即使是這種用情況最好還是盡可能限定變量的作用域,而且注意不要因?yàn)榱粼谘h(huán)使用的buffer中的數(shù)據(jù)引發(fā)錯(cuò)誤。這是安全錯(cuò)誤的一個(gè)常見來源。
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(實(shí)施建議)
Flag recycled variables.
標(biāo)記循環(huán)使用的變量。
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es26-dont-use-a-variable-for-two-unrelated-purposes
覺得本文有幫助?請(qǐng)分享給更多人。
關(guān)注微信公眾號(hào)【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
