C++核心準(zhǔn)則C.62:保證拷貝賦值對(duì)自我賦值安全

C.62:保證拷貝賦值對(duì)自我賦值安全
Reason(原因)If x = x changes the value of x, people will be surprised and bad errors will occur (often including leaks).
如果x=x改變了x的值,人們會(huì)覺(jué)得很奇怪,同時(shí)也會(huì)發(fā)生很不好的錯(cuò)誤。(通常會(huì)包含泄露)
Example(示例)The standard-library containers handle self-assignment elegantly and efficiently:
標(biāo)準(zhǔn)庫(kù)容器處理自我賦值的方式優(yōu)雅且高效:
std::vector v = {3, 1, 4, 1, 5, 9};
v = v;
// the value of v is still {3, 1, 4, 1, 5, 9}
Note(注意)The default assignment generated from members that handle self-assignment correctly handles self-assignment.
產(chǎn)生于正確處理了自我賦值的成員的默認(rèn)的賦值操作會(huì)處理自我賦值問(wèn)題。
struct Bar {
? ?vector> v;
? ?map m;
? ?string s;
};
Bar b;
// ...
b = b; ? // correct and efficient
Note(注意)You can handle self-assignment by explicitly testing for self-assignment, but often it is faster and more elegant to cope without such a test (e.g., using swap).
你可以通過(guò)明確地對(duì)自我賦值進(jìn)行檢查的方式防止自我賦值,但是通常不使用上述檢查的處理方式(例如使用swap)的方式更快,更優(yōu)雅。
class Foo {
? ?string s;
? ?int i;
public:
? ?Foo& operator=(const Foo& a);
? ?// ...
};
Foo& Foo::operator=(const Foo& a) ? // OK, but there is a cost
{
? ?if (this == &a) return *this;
? ?s = a.s;
? ?i = a.i;
? ?return *this;
}This is obviously safe and apparently efficient. However, what if we do one self-assignment per million assignments? That's about a million redundant tests (but since the answer is essentially always the same, the computer's branch predictor will guess right essentially every time). Consider:
這種做法看起來(lái)安全并且高效。但是如果在一百萬(wàn)次賦值中只發(fā)生一次自我賦值的情況下會(huì)怎么樣呢?大概有一百萬(wàn)次多余的檢查(但是由于本質(zhì)上結(jié)果總是一樣的,計(jì)算機(jī)的分支預(yù)測(cè)會(huì)每次都猜對(duì))??紤]下面的代碼:
Foo& Foo::operator=(const Foo& a) ? // simpler, and probably much better
{
? ?s = a.s;
? ?i = a.i;
? ?return *this;
}std::string is safe for self-assignment and so are int. All the cost is carried by the (rare) case of self-assignment.
std::string對(duì)自我賦值安全,int也是。所有的代價(jià)都來(lái)自(極少)發(fā)生的自我賦值。
Enforcement(實(shí)施建議)(Simple) Assignment operators should not contain the pattern if (this == &a) return *this; ???
(簡(jiǎn)單)賦值運(yùn)算符不應(yīng)該包含以下的檢查:if (this == &a) return *this;
覺(jué)得本文有幫助?請(qǐng)分享給更多人。
關(guān)注【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_(kāi)發(fā),面向?qū)ο笏伎迹?/span>
