Tuesday, September 16, 2008

copy elision and copy-and-swap idiom

An updated writeup of the copy-and-swap idiom is now available on the More C++ Idioms wikibook. A comparison of two different styles of assignment operator is shown. First version accepts the parameter as pass-by-const-reference whereas the second version accepts it as pass-by-value. For some classes pass-by-value turns out to be more efficient as a copy of the object is elided when the right hand side is a rvalue.

11 comments:

Maarten said...

Won't that not be less efficient once R-Value references make it into mainstream?

Mike said...

Thats actually pretty interesting and makes alot of sense, I need to put more thought into my programming and memory management/optimization.

Btw, that site is a great resource Im suprised this is the first time I've came across it. Thanks.

Anonymous said...

Strictly speaking, in that example since the code is inline, the compiler should be able to optimize out the temporary for rvalue references in both the

String &operator=(String)
and
String &operator=(const String &)

cases. But if it was not inline than the first would be better.

maarten - When rvalue reference types come in C++0x, it would be the same good as the copy-in version. However rvalue references let you do similar optimizations in more different scenarios.

Sumant said...

Hi anonymous! If you are absolutely sure about that, consider adding that (with some more explanation) in the original More C++ Idioms/copy-and-swap text at an appropriate place. After all, it is a wiki.

Anonymous said...

This copy-and-swap "idiom" is the most ridiculous, inane, incomprehensible thing I have ever heard. You're doing a freaking copy. Just do the copy. Use common sense. There's no need to swap back and forth. What the hell. This is an example of people being too smart for their own good, over-complicating a very basic operation.

Sumant said...

Hi anonymous! (2nd), I agree that copy-and-swap idiom requires a programmer to put more thought than one would ideally like to. If you ain't worried about exception-safety, use the solution that your common sense tells you. However, common sense can rarely be a substitute for such a well thought, useful, and widely (STL) deployed technique that has to work not just for oversmart people but for millions of C++ programmers out there.

elision said...

Thanks for sharing this interesting post.

elisions said...

Thanks for sharing this interesting post.

wn said...

Thanks...

Eran Smith said...

Nice thing you found but is it work properly or it need some special programming tool??

xander345 said...

if you like c++ you can compile it online here: http://codecompiler.info/

32, 64 - windows & Linux - and more programming languages