Conteúdo do 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
#include <iostream> #include <memory> std::unique_ptr<int> uniquePtrBuilder() { return std::make_unique<int>(42); // builder function initializes a new unique pointer // and instantly returns it, transferring ownership to caller } int main() { // this will be the sole owner of the dynamically allocated integer 42 std::unique_ptr<int> myUniquePtr = uniquePtrBuilder(); if (myUniquePtr) std::cout << "Value from unique pointer: " << *myUniquePtr << std::endl; else std::cout << "Unique pointer is null." << std::endl; }
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.
Obrigado pelo seu feedback!