← C++

C++ · 10 / 24

Ownership, lifetime and move semantics

Transfer exclusive ownership and verify when a resource is released.

  • Large
  • Advanced
  • 90 min

Prerequisites: Classes, references, const and RAII

In this tutorial
  1. Define the contract
  2. Separate tools and build
  3. Check observable expectations
  4. Detect an incorrect change
  5. Run the exercise separately
  6. Interpret the verification boundary
  7. Exercise and solution
  8. Project context and sources

Download learning package

Setup and verification

GCC with C++20 and CMake 3.25 or newer. Python 3 is also required for the common verification entry point. Extract the learning package into a new folder and run python3 run_checks.py there. The script copies the included files into a temporary learning directory. It verifies the example and then the supplied solution there, preserving the original files. Required packages are downloaded on the first run.

Verified on 2026-10-21 on Linux x86_64. Check which owner is empty after the move and when destruction occurs. The solution extends the ownership path. A raw pointer must not bypass that lifetime contract.

A unique_ptr owns a resource exclusively. std::move is a conversion that enables a move. Assigning destination transfers ownership here. An existing reference does not become an owner.

Package contents and individual files

01Define the contract

unique_ptr owns one resource. std::move makes a value available for ownership transfer. It does not itself copy the object. The previous owner must subsequently be used only according to its valid remaining state.

main.cpp · cppOpen file
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
struct Vehicle {
  static inline int alive = 0;
  std::string name;
  explicit Vehicle(std::string value) : name(std::move(value)) { ++alive; }
  ~Vehicle() { --alive; }
  Vehicle(const Vehicle &) = delete;
  Vehicle &operator=(const Vehicle &) = delete;
};
void check(bool condition) {
  if (!condition)
    throw std::runtime_error("Ownership check failed");
}
int main() {
  {
    auto owner = std::make_unique<Vehicle>("Cart");
    Vehicle &view = *owner;
    auto destination = std::move(owner);
    check(!owner && destination && Vehicle::alive == 1);
    check(view.name == "Cart");
    destination.reset();
    check(Vehicle::alive == 0);
    // view is now dangling and must never be read.
  }
  check(Vehicle::alive == 0);
  std::cout << "ownership verified\n";
}

Run / check

python3 verify.py

02Separate tools and build

Put all files in a new folder. Read the compiler options and run verify.py. A failed command must propagate its exit code to the caller.

verify.py · pyOpen file
import subprocess

subprocess.run(["cmake", "-S", ".", "-B", "build"], check=True)
subprocess.run(["cmake", "--build", "build", "--config", "Release"], check=True)
subprocess.run(
    ["ctest", "--test-dir", "build", "-C", "Release", "--output-on-failure"], check=True
)

03Check observable expectations

Check which owner is empty after the move and when destruction occurs. The solution extends the ownership path. A raw pointer must not bypass that lifetime contract.

CMakeLists.txt · cmakeOpen file
cmake_minimum_required(VERSION 3.20)
project(learning LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_executable(lesson main.cpp)
enable_testing()
add_test(NAME behaviour COMMAND lesson)
Expected result

Check which owner is empty after the move and when destruction occurs. The solution extends the ownership path. A raw pointer must not bypass that lifetime contract.

04Detect an incorrect change

Change a checked condition or expected result. Verification must now fail. Restore the original version afterwards. A green process alone does not explain which property is protected.

05Run the exercise separately

Move destination into another owner and verify lifetime afterwards.

06Interpret the verification boundary

The moved unique_ptr is empty. The resource lives until its final exclusive owner resets it. A borrowed reference must have its last use before that reset.

Expected result

Verification finishes successfully and checks the conditions named in the example.

Your exercise

Move destination into another owner and verify lifetime afterwards.

Show the solution and explanation

The moved unique_ptr is empty. The resource lives until its final exclusive owner resets it. A borrowed reference must have its last use before that reset.

solution.cpp · cppOpen file
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
struct Vehicle {
  static inline int alive = 0;
  std::string name;
  explicit Vehicle(std::string value) : name(std::move(value)) { ++alive; }
  ~Vehicle() { --alive; }
  Vehicle(const Vehicle &) = delete;
  Vehicle &operator=(const Vehicle &) = delete;
};
void check(bool condition) {
  if (!condition)
    throw std::runtime_error("Ownership check failed");
}
int main() {
  {
    auto owner = std::make_unique<Vehicle>("Cart");
    Vehicle &view = *owner;
    auto destination = std::move(owner);
    check(!owner && destination && Vehicle::alive == 1);
    check(view.name == "Cart");
    auto final_owner = std::move(destination);
    check(!destination && final_owner && Vehicle::alive == 1);
    final_owner.reset();
    check(Vehicle::alive == 0);
    check(Vehicle::alive == 0);
    // view is now dangling and must never be read.
  }
  check(Vehicle::alive == 0);
  std::cout << "ownership verified\n";
}

Project context and sources

This independent learning project explores a topic in this technology area. Project references provide a pinned revision as architectural context. They do not imply that every library or feature introduced here is already used in that application.