Course Content
C++ Smart Pointers
C++ Smart Pointers
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).
unique_pointer_builder
#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
.
transferring_ownership
// 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.
passing_raw_pointer
// 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.
Thanks for your feedback!