Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Passing Around Unique Pointers | Unique Pointers
C++ Smart Pointers
course content

Course Content

C++ Smart Pointers

C++ Smart Pointers

1. Introduction to Smart Pointers
2. Unique Pointers
3. Shared Pointers
4. Weak Pointers
5. Advanced topics

book
Passing Around Unique Pointers

One of the primary reasons we choose pointers and dynamic memory allocation over static variables is the flexibility they offer in passing data throughout different sections of code. However, when it comes to unique pointers, the passing around gets a bit tricky.

When Returning from Builder Functions

One valid use case for passing a unique pointer is when you are returning from a builder function (a function which exists only to allocate/build resources).

cpp

unique_pointer_builder

copy
123456789101112131415
#include <iostream> #include <memory> std::unique_ptr<int> unique_ptr_builder() { return std::make_unique<int>(42); } int main() { // This will be the sole owner of the dynamically allocated integer 42 std::unique_ptr<int> p_unique = unique_ptr_builder(); if (p_unique) std::cout << "Value from unique pointer: " << *p_unique << std::endl; else std::cout << "Unique pointer is null." << std::endl; }

Using a builder function to create a unique pointer to an int value. Once the function returns, the unique_ptr in the main function starts pointing to the dynamic integer value.

When Transferring Ownership

It is also considered valid and safe to move a unique pointer. For example, you may transfer the ownership of a unique pointer from class A to class B.

h

transferring_ownership

copy
12345
// Create a unique pointer inside classA classA->source_ptr = std::make_unique<int>(42); // Later, move the ownership to classB, this is perfectly fine classB->target_ptr = std::move(sourcePtr);

When not to Pass Unique Pointers

Sharing a std::unique_ptr with the intention of multiple parties owning it is not suitable. This breaks the core concept of a unique pointer, as it should have only one owner.

You may create a unique pointer instance inside a class and then pass its raw pointer to an external library function. Such sharing is unsafe and can lead to hard-to-debug memory problems.

h

passing_raw_pointer

copy
12345
// Create a unique pointer. std::unique_ptr<std::string> p_unique = std::make_unique<int>(33); // Extract the raw pointer and pass it to an external class. ExternalClass obj(p_unique.get()); // Never do this, not safe.
question mark

When is it considered appropriate to pass a unique pointer?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 4
We're sorry to hear that something went wrong. What happened?
some-alt