C++ Language/Indirection/RvalueReferences/MoveSemantics

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Traditionally, a class could provide a "copy-constructor" CRType::CRType(const CRType& x) {...} and a "copy-assignment operator" CRType& CRType::operator=(const CRType& x) {...}. These would get used in several situations, such as the definition of oDesti by CRType oDesti(oSource); (where oSource had already been defined as a CRType object). If CRType is some kind of custom container, then these two functions are usually implemented by deeply copying all contained items, which might be computationally-expensive.

In modern software, these are supplemented by also programming "move-constructor" and "move-assignment operator" functions that are implemented by only transferring a payload handle. Function overloading can distinguish between move-constructor and copy-constructor, because the move-constructor parameter's type is a "rvalue-reference" CRType&&.

Additional information about move-semantics (includes interactive examples)