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.
Unit testing your template code comes up from time to time. (You test your templates, right?) Some templates are easy to test. No others. Sometimes it's not clear how to about injecting mock code into the template code that's under test. I've seen several reasons why code injection becomes challenging. Here I've outlined some examples below with roughly increasing code injection difficulty. Template accepts a type argument and an object of the same type by reference in constructor Template accepts a type argument. Makes a copy of the constructor argument or simply does not take one Template accepts a type argument and instantiates multiple interrelated templates without virtual functions Lets start with the easy ones. Template accepts a type argument and an object of the same type by reference in constructor This one appears straight-forward because the unit test simply instantiates the template under test with a mock type. Some assertion might be tested in...
Comments
Btw, that site is a great resource Im suprised this is the first time I've came across it. Thanks.
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.