typestar

unique_ptr ownership in C++

One owner at a time: std::unique_ptr deletes what it holds, and only std::move can pass it on.

#include <memory>
#include <string>
#include <utility>

struct Job {
    std::string name;
    int priority;
};

std::unique_ptr<Job> handoff() {
    auto job = std::make_unique<Job>("index", 3);
    job->priority = 1;
    std::unique_ptr<Job> owner = std::move(job);  // job is now null
    return owner;
}

How it works

  1. std::make_unique<Job> allocates and constructs in one call; no bare new anywhere.
  2. -> reaches through the pointer to the Job members, same as a raw pointer would.
  3. std::move transfers the allocation to owner, leaving job null; returning moves it again, out to the caller.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
283
Tokens
81
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 69 seconds.

Type this snippet

Step 3 of 3 in Classes & RAII, step 18 of 27 in Language basics.

← Previous Next →