Sole ownership can change hands without creating a second owner. A unique pointer cannot be copied, but it can be moved. After a successful move from one unique pointer into another, the destination owns the object and the source is empty. The object itself need not be copied.
std::move, declared in <utility>, marks an expression as eligible to supply a movable value. It does not perform the transfer by itself. The receiving type's move construction or move assignment performs that work. For std::unique_ptr, assigning target = std::move(source) transfers ownership into target. If target already owns a different object, move assignment also releases that old object. In this lesson, the destination starts empty, so only the ownership transfer is visible.
The source variable still exists afterward. In this particular type, its defined moved-from state is empty, so compare it with nullptr or use it as a boolean before any access. Never dereference an empty unique pointer. Do not assume every moved-from type becomes empty: other library types have their own guarantees.
#include <iostream>
#include <memory>
#include <utility>
int main() {
std::unique_ptr<int> incoming = std::make_unique<int>(11);
std::unique_ptr<int> active = std::move(incoming);
std::cout << (incoming == nullptr) << '\n';
if (active) { std::cout << *active << '\n'; }
}
The example prints 1 then 11: the source is empty, but the same integer is still available through its new owner. In the starter, active already exists, so use move assignment at the marked line rather than declaring another variable. Leave the two output checks in place. Together they show that ownership left prepared and arrived in active without reading through the empty source.
The two arrows describe different times, not shared ownership. After the move, a is empty and b owns the same allocated integer.
prepared into active with std::move. The probes should print Source empty: 1 and Active: 45 without reading through the emptied source.Edit main.cpp, then press Run to inspect the Console. Press Submit to check your work. Keep the supplied probes in place.