skip to content

In C++, when should a function take std::unique_ptr<T> by value, by reference, or a plain T* or T& instead?

level: middleimportance: must knowfreq 70%

answer

  1. does the callee keep it?
  2. by value means sink
  3. reference to reseat the caller's
  4. borrow with T& or T*
  5. const unique_ptr& adds nothing

basics

~10 s

Take std::unique_ptr<T> by value when the function takes ownership, std::unique_ptr<T>& only when it must reset or replace the caller's pointer, and T& (or T* when null is allowed) when it merely uses the object.

solid answer

~40 s

The parameter type should say what happens to ownership. **By value**, `void adopt(std::unique_ptr<Node> child)`, is a sink: the caller must write `std::move`, and after the call the caller's pointer is empty whatever the callee does. **By non-const reference**, `std::unique_ptr<Node>&`, is for a function that may reset or replace the caller's pointer. A function that only **uses** the object takes `Node&` or `const Node&`, or `Node*` when "no node" is a valid input; it then works for objects owned by a `unique_ptr`, a `shared_ptr`, a container or the stack, and the convention is that a raw pointer never owns. `const std::unique_ptr<Node>&` is the type to avoid: it cannot transfer anything, yet it restricts callers to that exact owner type and adds an indirection. Factories return `std::unique_ptr<T>` by value.

code

cpp · 39 lines
cpp
#include <cstdio>
#include <memory>
#include <string>
#include <utility>
#include <vector>

struct Node {
    std::string name;
    std::vector<std::unique_ptr<Node>> children;
    explicit Node(std::string n) : name(std::move(n)) {}
};

void adopt(Node& parent, std::unique_ptr<Node> child) {     // sink: takes ownership
    parent.children.push_back(std::move(child));
}
void replace(std::unique_ptr<Node>& slot, std::string name) { // may reseat the caller's pointer
    slot = std::make_unique<Node>(std::move(name));
}
std::size_t count(const Node& n) {                           // only uses the object
    std::size_t total = 1;
    for (const auto& c : n.children) total += count(*c);
    return total;
}
const Node* find(const Node* n, const std::string& name) {   // nullable, non-owning
    if (n == nullptr || n->name == name) return n;
    for (const auto& c : n->children)
        if (const Node* hit = find(c.get(), name)) return hit;
    return nullptr;
}

int main() {
    auto root = std::make_unique<Node>("root");
    auto panel = std::make_unique<Node>("panel");
    adopt(*panel, std::make_unique<Node>("label"));
    adopt(*root, std::move(panel));                          // panel is now null
    replace(root->children[0]->children[0], "button");
    std::printf("%zu %s %d\n", count(*root),
                find(root.get(), "button") ? "found" : "missing", panel == nullptr);
}

go deeper

for a junior

Remember the three spellings: unique_ptr by value takes ownership, T& or T* borrows, and the caller writes std::move to hand ownership over.

for a middle

Explain why by-value is the right sink, when a non-const unique_ptr reference is justified, and why const unique_ptr& is a borrow in disguise.

for a senior

Review signatures for ownership leaks: sinks that only read, borrows stored past the call, and && sinks whose callers cannot tell whether they still own anything.

for a principal

Signatures are the cheapest ownership documentation a codebase has; insist that every parameter's type answers who owns the object.

## The question behind every signature When a function receives an object that lives on the heap, the parameter type answers one question for the reader: **does this function take ownership, change the caller's ownership, or only borrow the object for the duration of the call?** C++ gives a distinct spelling to each answer, and `std::unique_ptr` makes the first two checkable by the compiler. | parameter | meaning | call site | |---|---|---| | `std::unique_ptr<Node>` | sink: the function takes ownership | `adopt(std::move(p))` | | `std::unique_ptr<Node>&` | may reset or replace the caller's pointer | `replace(p)` | | `Node&` / `const Node&` | borrows a node that must exist | `count(*p)` | | `Node*` / `const Node*` | borrows a node that may be absent | `find(p.get())` | | `const std::unique_ptr<Node>&` | nothing the rows above do not do better | avoid | ## Sinks take the unique_ptr by value A by-value parameter is move-constructed from the argument at the call. Because `unique_ptr` is move-only, an lvalue argument is rejected — clang reports "call to implicitly-deleted copy constructor" — so the caller must write `std::move(p)`, which marks the hand-off in the source. After the call the caller's pointer is guaranteed empty, even if the function returns early, because the parameter itself took the pointer; if the function does not store it, the parameter's destructor deletes the object. A sink declared as `std::unique_ptr<Node>&&` looks similar but behaves differently: nothing moves until the callee moves from the reference, so an early return leaves ownership with the caller, and the signature no longer tells the caller what state its pointer is in. ## References to unique_ptr are for reseating `void replace(std::unique_ptr<Node>& slot, std::string name)` can assign a new node to the caller's pointer, reset it or move from it. That is the only reason to pass the smart pointer by non-const reference. A `const std::unique_ptr<Node>&` parameter can do none of those things; it is a borrow in disguise that: - refuses objects owned any other way (by a `std::shared_ptr`, by value in a container, on the stack); - costs an extra load, since the callee reads the `unique_ptr` and then the node (at -O2 clang emits two loads where a `Node*` parameter needs one); - protects only the pointer, not the node: `p->name = "x"` still compiles through it. ## Borrowing uses plain references and pointers A function that only reads or modifies the node during the call takes `Node&`/`const Node&`, or `Node*`/`const Node*` when null is meaningful. Under the usual convention a **raw pointer never owns**: the callee must not delete it and must not store it past the call unless the owner's lifetime is known to be longer. Callers pass `*p` or `p.get()`. A borrow also keeps the function usable by callers who own the object differently. `count(const Node&)` accepts `*unique`, `*shared`, a stack object or a vector element; `count(const std::unique_ptr<Node>&)` accepts only the first. Library code that is written against borrows can be reused when an owner later changes from `unique_ptr` to `shared_ptr` or to a value member, without touching a single signature. ## Ownership that may or may not be taken Sometimes a function decides at run time whether to keep an object — an `adopt` that rejects a child whose name is already taken, for instance. Two honest spellings exist: 1. Take the `unique_ptr` by value and **return** it when rejected (`std::unique_ptr<Node> try_adopt(std::unique_ptr<Node> child)`, returning `nullptr` on success and the child on failure), so the caller always knows where the object is. 2. Take a borrow, decide, and let the caller move the object in a second call only after acceptance. Taking `std::unique_ptr<Node>&&` and moving only on success also works, but the caller then cannot tell from the call site alone whether its pointer was emptied. ## Returning 1. Factories return `std::unique_ptr<T>` by value; the caller becomes the owner. 2. Accessors that expose an owned child return `T&` or `T*`; the parent keeps ownership. 3. A function that gives ownership back, such as detaching a child from its parent, returns `std::unique_ptr<T>` by value. ## Common mistakes - Passing `const std::unique_ptr<T>&` "to avoid a copy" — there was never a copy to avoid. - Taking `std::unique_ptr<T>` by value in a function that only reads the object, which forces callers to give up ownership. - Storing a borrowed `T*` in a long-lived structure without proof that the owner outlives it.

  • What changes if a sink takes std::unique_ptr<Node>&& instead of std::unique_ptr<Node> by value?
    The caller still writes `std::move`, but nothing moves until the callee moves from the reference. If the callee returns early or throws first, the caller keeps ownership, so the caller cannot tell from the signature whether its pointer is now empty. By value, the parameter takes the pointer at the call, so the caller's pointer is always empty afterwards.
  • Why is const std::unique_ptr<T>& a poor parameter type?
    It cannot transfer or reset ownership, so it says no more than `const T&` or `const T*`, yet it only accepts objects owned by a `unique_ptr` of that exact type. It also adds an indirection, and its `const` protects the pointer, not the object, so the callee can still modify `*p`.

  • Passing unique_ptr by const reference is the efficient way to share it
  • A raw pointer parameter means the callee will delete the object
  • A unique_ptr&& parameter guarantees the move happened
  • Functions should take whatever smart pointer type the caller holds
  • Taking T& instead of unique_ptr gives up ownership safety