A Move Example

Let’s look at an example to see how move semantics and rvalue references work. Listing 18.2 defines and uses the Useless class, which incorporates dynamic memory allocation, a regular copy constructor, and a move constructor, which uses move semantics and an rvalue reference. In order to illustrate the processes involved, the constructors and destructor are unusually verbose, and the class uses a state variable to keep track of the number of objects. Also some important methods, such as the assignment operator, are omitted. (Despite these omissions, the Useless class should not be confused with the eco-friendly Use_Less class.)

Listing 18.2. useless.cpp

// useless.cpp -- an otherwise useless class with move semantics#include <iostream> ...

Get C++ Primer Plus now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.