C++核心準則ES.5: 盡量壓縮作用域

ES.5: Keep scopes small
ES.5: 盡量壓縮作用域
Reason(原因)
Readability. Minimize resource retention. Avoid accidental misuse of value.
可讀性。最小化資源的保持時間。避免變量的誤用。
Alternative formulation: Don't declare a name in an unnecessarily large scope.
換個說法:不要沒有必要擴大名稱的作用域。
Example(示例)
void use()
{
int i; // bad: i is needlessly accessible after loop
for (i = 0; i < 20; ++i) { /* ... */ }
// no intended use of i here
for (int i = 0; i < 20; ++i) { /* ... */ } // good: i is local to for-loop
if (auto pc = dynamic_cast(ps)) { // good: pc is local to if-statement
// ... deal with Circle ...
}
else {
// ... handle error ...
}
}
Example, bad(反面示例)
void use(const string& name)
{
string fn = name + ".txt";
ifstream is {fn};
Record r;
is >> r;
// ... 200 lines of code without intended use of fn or is ...
}
This function is by most measure too long anyway, but the point is that the resources used by?fn?and the file handle held by?is?are retained for much longer than needed and that unanticipated use of?is?and?fn?could happen later in the function. In this case, it might be a good idea to factor out the read:
這個函數(shù)用任何標準衡量都太長了,但是要點在于fn使用的資源和is管理的文件被維持的時間遠遠超過需要,有可能在函數(shù)接下來的部分is和fn會被意外使用。這種情況下,分解出一個read函數(shù)可能是一個好主意。
Record load_record(const string& name)
{
string fn = name + ".txt";
ifstream is {fn};
Record r;
is >> r;
return r;
}
void use(const string& name)
{
Record r = load_record(name);
// ... 200 lines of code ...
}Enforcement(實施建議)
Flag loop variable declared outside a loop and not used after the loop
標記在循環(huán)外定義循環(huán)變量并且循環(huán)之后不再使用的情況。
Flag when expensive resources, such as file handles and locks are not used for N-lines (for some suitable N)
標記高價值資源(例如文件句柄和鎖)在N行(適當值)之內(nèi)沒有使用的情況。
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es5-keep-scopes-small
覺得本文有幫助?請分享給更多人。
關(guān)注微信公眾號【面向?qū)ο笏伎肌枯p松學習每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
