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

Зміст курсу

C++ Smart Pointers

C++ Smart Pointers

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

book
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).

cpp

uniquePtrBuilder

copy
123456789101112131415161718
#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.

When is it considered appropriate to pass a unique pointer?

When is it considered appropriate to pass a unique pointer?

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 2. Розділ 4
We're sorry to hear that something went wrong. What happened?
some-alt