Contenido del Curso
C++ Smart Pointers
C++ Smart Pointers
Passing Around Unique Pointers
When is it okay to pass 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.
Note
There are certain best practices that you should follow when accessing unique pointers beyond the scope in which they were initialized.
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).
uniquePtrBuilder
In the above code, we are using a builder function to create a unique pointer to an integer value. Once the function returns, the myUniquePtr
in the main
function starts pointing to the dynamic integer value.
When transferring ownership
It’s 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
.
When is it not okay 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.
For example, 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.
¿Todo estuvo claro?