Friday, September 12, 2014

C++: copy elision

The C++ standard permits the compiler to skip (or "elide") a constructor under some circumstances, e.g. when a temporary is passed into a function by value. There is plenty of information on the web about this subject, but here is a concrete example.

What's interesting is that "copy elision" can actually alter semantics:
When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the copy/move constructor and/or destructor for the object have side effects.
Anyway, because of this feature, it can be wise to let a method accept an input by value rather than by const-reference, e.g.
table[key] = value;
The pattern should be considered whenever the method would have created an explicit copy, as for swapping.

No comments:

Post a Comment