Sub topic 2
Move construction and move assignment
Two ways to move
A move operation creates or changes an object using resources from another object. A resource is something a program manages, such as allocated memory. Moving can avoid copying that resource, but the cost depends on the type.
A move constructor creates a new object from an existing object. A move assignment operator replaces the value of an object that already exists.
For example, creating a new string from another string can use a move constructor. Giving an existing string a new value can use move assignment. The two operations may transfer resources differently.
Using `std::move`
std::move marks an object as eligible to be moved from. It produces an rvalue expression, which can be used to select a move operation. It does not move anything by itself.
A move is not guaranteed. For example, moving from a const string usually selects a copy instead, because moving would need to change the source.
After a move
A moved-from object is the source of a move. Most moved-from standard library objects are valid but have an unspecified value: do not assume they are empty or retain their old value.
You can destroy a moved-from string or assign it a new value. Other operations may have requirements, so check the type’s documentation. User-defined types set their own moved-from guarantees.
Move-only ownership
A move-only type can be moved but not copied. std::unique_ptr is a move-only object that owns a resource: it is responsible for deleting that resource when ownership ends.
Moving a std::unique_ptr transfers ownership. The source pointer becomes null, meaning it no longer points to the resource.
This complete example shows both kinds of move:
#include <iostream>
#include <memory>
#include <string>
#include <utility>
int main() {
std::string original = "hello";
// Move construction: destination is a new object.
std::string destination = std::move(original);
// Move assignment: target already exists.
std::string target = "old value";
target = std::move(destination);
// A moved-from string can be assigned a new value.
original = "reused";
auto first = std::make_unique<int>(42);
auto second = std::move(first);
std::cout << target << '\n';
std::cout << original << '\n';
std::cout << *second << '\n';
std::cout << std::boolalpha << (first == nullptr) << '\n';
}The program prints hello, reused, 42, and true on separate lines. The expression *second reads the owned integer.
Exercise
Which line uses move assignment, and what is the value of first after its move?
Show answer
The line target = std::move(destination) uses move assignment. After its move, first is null.