Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
910 views
in Technique[技术] by (71.8m points)

c++ - vector.push_back rvalue and copy-elision

I push_back a temporary object into a vector like this,

vector<A> vec;
vec.push_back(A("abc"));

will the compiler apply copy-elision to construct the temporary A("abc") directly into the vector, so that A's copy ctor won't be triggered when pushing the temporary object into vec.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you have a compiler that supports rvalue references, it will be moved into the vector, which is sometimes quite cheap.

An alternative to that is to directly construct the object in the vector, which can be done with vec.emplace_back("abc");. This only invokes one constructor.

Both of these are C++11 features. Copy elision is not allowed here, so without those features the copy will still be made.

However, if the copy constructor has no observable side-effects (which it shouldn't have anyway), a smart compiler may still perform that optimisation, because the "as-if" rule allows any optimisation that results in the same observable behaviour. I don't know if any current compiler does that, though. If not, I doubt anyone will spend the effort to add such an optimisation because rvalue references put an end to that need.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...