← C++

C++ · 04 / 24

Classes, references, const and RAII

Group vehicle data into a type and observe automatic resource cleanup when a scope ends.

  • Medium
  • Intermediate
  • 60 min

Prerequisites: Strings, vectors and standard algorithms

In this tutorial
  1. Read the vehicle type
  2. Distinguish reference from copy
  3. Observe single ownership
  4. Inspect the verification
  5. Connect the rule to the app
  6. Exercise and solution
  7. 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. The console run shows ownership and destruction order. The solution moves the scope boundary to expose the different lifetime.

A vehicle has related data and behavior. A class groups both. public identifies operations available to callers, while private protects implementation details. Its constructor creates an initial state and its destructor runs at the end of the object’s lifetime.

RAII associates a resource with an object whose lifetime is clearly bounded. std::string and std::vector already used this principle. We now also examine std::unique_ptr as the single owner of a dynamically created object. The finished app keeps simple vehicle data as values. Not every object should be placed behind a pointer.

Package contents and individual files

01Read the vehicle type

Vehicle receives a name during construction. The initializer after the colon sets name_ before the constructor body runs. std::move allows ownership of the supplied string storage to be transferred. The name method supplies read-only access to the stored name. Callers cannot arbitrarily change the private field.

main.cpp · cppOpen file
#include <iostream>
#include <memory>
#include <string>
#include <utility>
class Vehicle {
public:
  explicit Vehicle(std::string name) : name_(std::move(name)) {}
  ~Vehicle() { std::cout << "released=" << name_ << '\n'; }
  const std::string &name() const { return name_; }

private:
  std::string name_;
};
void printName(const Vehicle &vehicle) {
  std::cout << "vehicle=" << vehicle.name() << '\n';
}
int main() {
  {
    auto vehicle = std::make_unique<Vehicle>("Cart 1");
    printName(*vehicle);
  }
  std::cout << "scope_finished=true\n";
}

Run / check

g++ -std=c++20 main.cpp -o lesson
./lesson

02Distinguish reference from copy

printName accepts const Vehicle&. The ampersand declares a reference to the existing vehicle rather than creating another vehicle. const prevents modification through that reference. A reference does not own the object and must not be used after the referenced vehicle’s lifetime ends.

03Observe single ownership

std::make_unique creates the vehicle and returns its owner. The star before vehicle accesses the owned object. The inner block ends before the final output. Leaving that block destroys the unique_ptr and automatically destroys the vehicle. The destructor output exposes the cleanup point.

Expected result

vehicle=Cart 1 released=Cart 1 scope_finished=true

04Inspect the verification

The console run shows ownership and destruction order. The solution moves the scope boundary to expose the different lifetime.Run python3 run_checks.py from the extracted package. Compare the test expectations with the exercise before opening the solution.

Expected result

The example and automated solution pass. The stated manual checks remain separate.

05Connect the rule to the app

FactoryForge holds the simulation through a single owner. Its stoppable thread finishes before the simulation is released. Maps and vehicle snapshots are copied as values instead. Ownership and lifetime determine the choice. References, pointers and independent snapshots are not interchangeable solutions.

Your exercise

Move the final output into the inner block. Which message appears first now? Explain why a reference to the released vehicle would be invalid.

Show the solution and explanation

Inside the block, scope_finished appears before released because the owner is still alive. The vehicle is destroyed at the closing brace. A stored reference does not extend its lifetime and cannot be read afterwards. Keep the owner alive while access is needed or transfer an independent value.

solution/main.cpp · cppOpen file
#include <iostream>
#include <memory>
#include <string>
#include <utility>
class Vehicle {
public:
  explicit Vehicle(std::string name) : name_(std::move(name)) {}
  ~Vehicle() { std::cout << "released=" << name_ << '\n'; }
  const std::string &name() const { return name_; }

private:
  std::string name_;
};
void printName(const Vehicle &vehicle) {
  std::cout << "vehicle=" << vehicle.name() << '\n';
}
int main() {
  {
    auto vehicle = std::make_unique<Vehicle>("Cart 1");
    printName(*vehicle);
    std::cout << "scope_finished=true\n";
  }
}

Project context and sources

The first six examples are standalone teaching programs. Lessons 7 through 9 use the complete FactoryForge source snapshot. Code, exercises and verified simplifications are explained separately. The project page provides a source ZIP while the GitHub repository is not yet published.