日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

vector c++ 赋值_面对拷贝赋值时发生的自我赋值的正确态度时接受而不是防止

發布時間:2023/12/2 c/c++ 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 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).

你可以通過明確地對自我賦值進行檢查的方式處理自我賦值,但是通常不使用上述檢查的處理方式(例如使用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++ 赋值_面对拷贝赋值时发生的自我赋值的正确态度时接受而不是防止的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。