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

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > c/c++ >内容正文

c/c++

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

發(fā)布時(shí)間:2023/12/2 c/c++ 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 vector c++ 赋值_面对拷贝赋值时发生的自我赋值的正确态度时接受而不是防止 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

C.62: Make copy assignment safe for self-assignment
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)都會(huì)更快,更優(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)分享給更多人。

更多精彩文章請(qǐng)關(guān)注微信公眾號(hào)【面向?qū)ο笏伎肌?#xff01;

面向?qū)ο箝_(kāi)發(fā),面向?qū)ο笏伎?#xff01;

總結(jié)

以上是生活随笔為你收集整理的vector c++ 赋值_面对拷贝赋值时发生的自我赋值的正确态度时接受而不是防止的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。