CodeTheRobot

C++ Intermediate · Lesson 02 of 27

Smart pointers: std::unique_ptr

Exclusive ownership, make_unique, transferring ownership and returning from functions.

Estimated time · 45–75 min

Learning goals

What you will understand

  • Explain smart pointers: std::unique_ptr in your own words
  • Use it in a small robotics example
  • Verify the result instead of assuming it worked

Understand the idea first

The mental model

std::unique_ptr<T> owns exactly one object and deletes it when the pointer is destroyed. It cannot be copied, only moved, so ownership is always clear. Create it with std::make_unique<T>(args...), never with new.

Default to unique_ptr for anything on the heap. Pass a raw pointer or reference to a function that only uses the object, and pass the unique_ptr by value (with std::move) only to give ownership away.

Guided lesson

Work through these steps

  1. 1.

    Read the smart pointers: std::unique_ptr example and identify what each line owns or changes.

  2. 2.

    Create a small source file, compile with -std=c++17 and warnings enabled, and run it.

  3. 3.

    Change one input, predict the result before running, then compare the output.

  4. 4.

    Record one compiler or runtime error and explain the correction in your own words.

Worked example

Read it before you run it

#include <memory>
// Header for unique_ptr, shared_ptr and weak_ptr.
struct MotorDriver { void start() {} };
// A stand-in driver class.
auto driver = std::make_unique<MotorDriver>();
// Create the driver on the heap with one owner; no new or delete.
driver->start();
// -> reaches the object, exactly like a raw pointer.
auto other = std::move(driver);
// Transfer ownership; driver is now empty (nullptr).
if (!driver) std::cout << "moved out\n";
// A moved-from unique_ptr tests false.
std::unique_ptr<MotorDriver> make() { return std::make_unique<MotorDriver>(); }
// A factory that returns ownership to the caller.
auto fresh = make();
// The returned pointer is moved into fresh automatically.
// other and fresh are deleted automatically at the end of the scope.
// No delete anywhere: RAII does the cleanup.

What the example is doing

  1. 1.Read declarations from right to left: identify each value's type, name, and initial value.
  2. 2.Follow the data through each expression before considering syntax shortcuts.
  3. 3.Compile with warnings enabled; a clean build is part of the result, not an optional polish step.

Watch it run · Values in memory

See what this code does

The terminal types this lesson's practice solution and runs it. The scene shows the kind of robot behaviour that code drives. It plays by itself and loops.

motor speed030x1070x1410x1890x1c40x2060x2420x2880x2c*p += 10VALUES IN MEMORY

Demo for Smart pointers: std::unique_ptr. Expected result: created a empty destroyed

Practice code

Now type it yourself

Copy the starter into practice.cpp and replace every TODO with your own code. Build and run it: g++ -std=c++17 -Wall -Wextra -Wpedantic practice.cpp -o practice -pthread && ./practice

#include <iostream>
#include <memory>

struct Driver {
  Driver() { std::cout << "created\n"; }
  ~Driver() { std::cout << "destroyed\n"; }
};

int main() {
  // TODO: make a unique_ptr<Driver> named a with make_unique, then move it into b
  std::cout << (a ? "a owns it" : "a empty") << '\n';
  return 0;
}

Expected output

created
a empty
destroyed
Stuck? Show the full solution (try it yourself first)
#include <iostream>
#include <memory>

struct Driver {
  Driver() { std::cout << "created\n"; }
  ~Driver() { std::cout << "destroyed\n"; }
};

int main() {
  auto a = std::make_unique<Driver>();
  auto b = std::move(a);
  std::cout << (a ? "a owns it" : "a empty") << '\n';
  return 0;
}

Expected result

How you know it worked

  • After adding the shown fragment to the guided exercise with its listed headers and surrounding program, the finished program builds with -Wall -Wextra -Wpedantic.
  • Changing the stated input produces the result you predicted.

Practical exercise

Apply the lesson

Write a factory returning std::unique_ptr<MotorPort>. Store two in a vector, transfer one to another owner with std::move, and prove each is destroyed exactly once by logging in the destructor.

Before you continue

  • The program builds with -std=c++17 and no warnings
  • You can explain the key rule without reading the example
  • The normal and edge cases both have recorded results

If something goes wrong

The compiler reports that a name or type is unknown.

Start at the first error. Check spelling, required #include lines, and whether the declaration appears before use.

The program runs but the value is wrong.

Print the inputs and intermediate values, then check conversions, units, and collection order.