Skip to content
C++ Basics: Transfer Ownership with std::unique_ptr

C++ Basics: Transfer Ownership with std::unique_ptr

November 2, 2026

Move a unique pointer into a function and observe the empty source without leaking or manually deleting memory.

Prepare a scratch directory

Tested on Linux x86_64 with GCC 14.2.0. Install a C++20-capable GCC compiler and its standard-library development files, with g++ on PATH. You also need Bash, a text editor, and mktemp, rm, and rmdir. No third-party library is required.

Keep the same terminal open. Stop if setup fails before saving the source:

start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1

Run the example

Save this as unique-pointer-transfer-demo.cpp:

#include <iostream>
#include <memory>
#include <utility>

void consume_value(std::unique_ptr<int> owned_value)
{
    std::cout << "Received: " << *owned_value << '\n';
}

int main()
{
    auto original_owner = std::make_unique<int>(42);
    consume_value(std::move(original_owner));
    std::cout << std::boolalpha
              << "Source is empty: " << (original_owner == nullptr) << '\n';
}

Compile and run it. The second command runs only after compilation succeeds:

g++ -std=c++20 -Wall -Wextra -Werror -pedantic unique-pointer-transfer-demo.cpp -o unique-pointer-transfer-demo &&
./unique-pointer-transfer-demo

Observed output:

Received: 42
Source is empty: true

Read the result

The function parameter takes ownership by value. Moving the pointer transfers its managed object; the source becomes empty. The function reads the value, then its parameter destroys the integer automatically when the call returns.

Apply it carefully

Use a reference or a non-owning pointer when a function only borrows an object. Taking unique_ptr by value signals an ownership transfer. Do not dereference the moved-from pointer; it can be tested, reset or assigned a new owner. This example passes a non-null pointer, so the function does not need to handle a null argument.

The C++ working draft documents the relevant behavior. This example uses C++20 features, not newer additions shown elsewhere in the current draft.

Clean up

Remove only the source and executable created here, then remove the empty practice directory:

rm -- unique-pointer-transfer-demo.cpp unique-pointer-transfer-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directory

If the directory is not empty, inspect its remaining contents before removing anything else.

Acknowledgements

This post was created with assistance from AI.

Last updated on