skip to content

In C++, what do std::unique_ptr's release(), reset() and get() each do, and which one leaks when misused?

level: middleimportance: should knowfreq 55%

answer

  1. who owns afterwards?
  2. get keeps ownership
  3. release gives up without deleting
  4. reset deletes the old object
  5. an ignored return value

basics

~20 s

get() returns the pointer and keeps ownership; release() returns it and gives up ownership without deleting; reset(p) deletes the old object and owns p. Ignoring release()'s result leaks, and deleting get()'s result causes a double delete.

solid answer

~40 s

All three touch the stored pointer, but they differ in ownership. `get()` is an observer: it returns the address and the `unique_ptr` still owns the object, so the result may be used as a borrow but never deleted or adopted by another owner. `release()` returns the address and sets the stored pointer to null **without** deleting anything; the caller now owns the object, so `p.release();` on its own line is a leak. Neither libc++ nor libstdc++ marks `release()` `[[nodiscard]]`, and clang -Wall stays silent. `reset(q)` stores `q` and then deletes the old object (the standard fixes that order); `reset()` with no argument just deletes and leaves the pointer null. Use `release()` only to hand the object to an API that takes ownership of a raw pointer, inside that call: `legacy_attach(p.release())`.

code

cpp · 25 lines
cpp
#include <cstdio>
#include <memory>
#include <string>

struct Node {
    std::string name;
    explicit Node(std::string n) : name(std::move(n)) {}
    ~Node() { std::printf("~%s\n", name.c_str()); }
};

void legacy_attach(Node* adopted) { delete adopted; }  // C-era API that takes ownership

int main() {
    auto a = std::make_unique<Node>("a");
    Node* observer = a.get();          // a still owns; observer must not delete
    std::printf("get: %s, a owns: %d\n", observer->name.c_str(), a != nullptr);

    a.reset(new Node("b"));            // stores "b", then deletes "a"
    legacy_attach(a.release());        // a gives up "b" without deleting it
    std::printf("after release, a owns: %d\n", a != nullptr);

    auto c = std::make_unique<Node>("c");
    c.reset();                         // deletes "c" now
    std::printf("end of main\n");
}

go deeper

for a junior

Know that get() only looks, release() gives ownership away without deleting, and reset() deletes the current object.

for a middle

Explain the ownership table for the three members, the reset ordering the standard fixes, and why an ignored release() result is a leak.

for a senior

Recognize the double delete from deleting or re-wrapping get(), the dangling pointer left by p.reset(p.get()), and release() placed before a call that can fail.

for a principal

Treat every release() as an ownership hand-off that needs a reviewer's eye, and keep the few legacy boundaries that need it in one place.

## Three members, three ownership outcomes `std::unique_ptr<T>` holds one stored pointer. Three member functions read or change it, and the difference between them is entirely about **who owns the object afterwards**. | member | returns | stored pointer afterwards | object deleted? | owner afterwards | |---|---|---|---|---| | `get()` | the address | unchanged | no | the `unique_ptr` | | `release()` | the address | `nullptr` | no | whoever took the return value | | `reset(q)` | nothing | `q` | the old one, yes | the `unique_ptr` (of `q`) | | `reset()` | nothing | `nullptr` | the old one, yes | nobody | ## get(): a borrow `get()` is `noexcept` and changes nothing. Its result is a non-owning pointer, useful for calling a function that takes `T*`. Two misuses turn it into a bug: - calling `delete p.get()` — the `unique_ptr` deletes the object again when it is destroyed or reset: a **double delete**; - wrapping it in a second owner, `std::unique_ptr<T> q(p.get())` — the same double delete, one owner later. A pointer from `get()` also **dangles** as soon as the `unique_ptr` is reset, reassigned or destroyed. ## release(): giving ownership away The standard specifies `release()` with the postcondition `get() == nullptr` and returns the value `get()` had before the call. It does not call the deleter. That makes it the tool for handing an object to code that takes ownership of a raw pointer — a C-era API, an intrusive container — and the source of a classic leak when its return value is ignored. The standard does not mark it `[[nodiscard]]`; neither do the pinned libc++ and libstdc++ headers, and `clang++ -Wall -Wextra` compiles `p.release();` without a warning. Good practice: 1. Call `release()` inside the call that takes ownership: `legacy_attach(p.release());`. 2. If the API can fail without taking ownership, pass `p.get()` first, check the result, and call `release()` only after success. 3. Never write `release()` just to "turn off" a `unique_ptr`; that is what `reset()` is for. ## reset(): replace and delete `reset(q)` is specified as: assign `q` to the stored pointer, **then** call the deleter on the old pointer if it was non-null. The order is deliberate — the standard notes that the deleter call might destroy `*this`, so the `unique_ptr` must already be in its new state. Consequences: - `p.reset(new Node("b"))` builds the new node first; if that `new` throws, `p` and its old node are untouched. - `p.reset(p.get())` stores the same address and then deletes it, leaving `p` holding a dangling pointer that it will delete again later. - `p.reset()` and `p = nullptr` are equivalent ways to delete the object early. ## How move assignment is built from them The standard specifies move assignment `p = std::move(q)` in terms of these members: it calls `reset(q.release())` and then moves the deleter. That one line shows the whole ownership dance — `q` gives its object up without deleting it, `p` stores it and deletes whatever it held before — and it also explains why `p = std::move(p)` leaves `p` owning its object: `release()` empties `p` first, so the following `reset` stores the same pointer back and finds nothing old to delete. `swap(q)` exchanges the pointers and deleters and deletes nothing. | operation | object that gets deleted | |---|---| | `p = std::move(q)` | the one `p` held before | | `p.swap(q)` | none | | `p = nullptr` | the one `p` held | | `q.release()` with the result ignored | none, and it leaks | ## In a scene graph A parent that owns its children through `std::vector<std::unique_ptr<Node>>` uses all three members in different places: 1. A renderer that only draws receives `child.get()` (or `*child`) and keeps nothing after the frame. 2. Rebuilding a child in place is `children[i].reset(new Node(...))`, or better, assigning the result of `std::make_unique<Node>(...)`; the old subtree is deleted after the new pointer is stored. 3. Handing a subtree to a legacy layer that frees nodes itself is the one place for `release()`, written inside the call that adopts it. In most code `release()` should be rare enough that each use is worth a review comment, and a `get()` result stored in a member deserves the same scrutiny, because it dangles the moment its owner resets.

  • What happens with p.reset(p.get()) on a non-null std::unique_ptr?
    reset stores its argument, then deletes the old pointer, which is the same object. `p` is left holding a dangling address, and when `p` is destroyed or reset again it deletes that address a second time: undefined behaviour. reset must be given a pointer the unique_ptr does not already own, or nothing.
  • How do you hand a unique_ptr's object to a C-style function that takes ownership only when it succeeds?
    Pass `p.get()`, check the function's result, and call `p.release()` only after success, discarding the result deliberately. If the call fails, `p` still owns the object and deletes it normally. Calling `release()` before the call would leak on failure.

  • release() deletes the object and sets the pointer to null
  • reset() and release() both free the memory
  • Calling delete on get() is fine if you reset afterwards
  • get() transfers ownership to the caller
  • reset(q) deletes the old object before storing q