Move semantics

As we've already discussed in this chapter, the creation of temporary objects was a real performance problem in classic (or should I say old?) C++, so one of the first innovations that was introduced in "modern" C++ was the possibility to mark some objects as throwaway objects. For example, the temporary objects created in the earlier example of operator chaining are only throwaway objects which just pass their data to the next operation.

This is suggestive of the notion of a movable object, that is an object that can give away (that is, move) its congaing data when it finds itself in a specific context. Such an object will define a move constructor and a move assignment operator and will bind to a new type of reference in function calls—a movable reference (called rvalue reference) denoted with &&:

struct X
{
std::string s;
// move constructor, it eats away the contents of x argument!
X(X &&x) : s(std::move(x.s)) {}
};

// function using move semantics
void func(X &&x);

In that manner, the problem with temporaries, which get created only to copy out their contents and then perish, was solved, or at least amended, by replacing it with movable objects that just pass their data further on. This alone can provide substantial performance gains.

There are much more technical details concerning move semantics, so if you want to learn more, please consult one of the books from the Further reading section.