The move constructor creates a new object that takes ownership of another object's external resources instead of copying them. By transferring ownership of the resource (e.g. heap memory, file handles, sockets), the underlying data is not reallocated thus cheaper to move. Built-in fields are instead copied.
The move constructor takes an rvalue reference (&&) argument:
class Buffer {
public:
Buffer(int n) : size(n), data(new int[n]) {}
Buffer(Buffer&& other) noexcept : size(other.size), data(other.data) {
// Invalidate moved-from object's fields to prevent accidental free and side-effects.
other.size = 0;
other.data = nullptr;
}
~Buffer() { delete[] data; }
int size;
int* data;
};Note
Mark the move constructor noexcept. Code that guarantees no change on failure (e.g. std::vector#include <vector> when it grows) only moves elements whose move constructor is noexcept. Otherwise, it will copy.
The move constructor is invoked when a new object is initialised from an rvalue (temporary or cast with std::move#include <utility>()):
std::vector#include <vector><Buffer> v;
v.push_back(Buffer(10)); // Moves the temporary into the vector.
Buffer a(1000);
Buffer b = std::move#include <utility>(a); // Moves a into b.
b.size; // 1000
a.data; // nullptrThe move constructor can be deleted to prevent usage:
class Buffer {
public:
Buffer(Buffer&&) = delete;
};
Buffer b = std::move#include <utility>(a); // ERROR.The move constructor can be defaulted to let the compiler generate it:
class Buffer {
public:
Buffer(Buffer&&) = default;
};Warning
The compiler-generated move constructor moves each field but does not invalidate the moved-from object's fields.
Dan