vector c++ 赋值_面对拷贝赋值时发生的自我赋值的正确态度时接受而不是防止
C.62: Make copy assignment safe for self-assignment
C.62:保證拷貝賦值對自我賦值安全
Reason(原因)
If x = x changes the value of x, people will be surprised and bad errors will occur (often including leaks).
如果x=x改變了x的值,人們會覺得很奇怪,同時也會發生很不好的錯誤。(通常會包含泄露)
Example(示例)
The standard-library containers handle self-assignment elegantly and efficiently:
標準庫容器處理自我賦值的方式優雅且高效:
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.
產生于正確處理了自我賦值的成員的默認的賦值操作會處理自我賦值問題。
struct Bar { ? ?vector> v; ? ?map m; ? ?string s;};Bar b;// ...b = b; ? // correct and efficientNote(注意)
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).
你可以通過明確地對自我賦值進行檢查的方式處理自我賦值,但是通常不使用上述檢查的處理方式(例如使用swap)都會更快,更優雅。
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:
這種做法顯然安全并且看起來高效。但是如果在一百萬次賦值中發生一次自我賦值的情況下會怎么樣呢?大概有一百萬次多余的檢查(但是由于本質上結果總是一樣的,計算機的分支預測會每次都猜對)??紤]下面的代碼:
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對自我賦值安全,int也是。所有的代價都來自(極少)發生的自我賦值。
Enforcement(實施建議)
(Simple) Assignment operators should not contain the pattern if (this == &a) return *this; ???
(簡單)賦值運算符不應該包含以下的檢查:if (this == &a) return *this;
覺得本文有幫助?請分享給更多人。
更多精彩文章請關注微信公眾號【面向對象思考】!
面向對象開發,面向對象思考!
總結
以上是生活随笔為你收集整理的vector c++ 赋值_面对拷贝赋值时发生的自我赋值的正确态度时接受而不是防止的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: tan的导数是什么
- 下一篇: 华为编程规范_华为 Java 编程规范出