Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Best Practices of Using Shared Pointers | Shared 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

Best Practices of Using Shared Pointers

Only use shared pointers when you can’t use unique

Unique pointers should always be your first consideration when allocating a dynamic object. Only revert to shared pointers if you can justify the need for sharing.

Initialize shared pointers at the point of declaration

To enhance code readability and maintainability, it’s recommended to initialize a shared pointer when you declare it. This practice ensures that the shared pointer points to a valid object from the start and reduces the chances of accessing a null or uninitialized pointer.

cpp

good

cpp

bad

Minimize the shared scope

While it's generally safe to use shared pointers, it's essential to exercise caution when sharing them. Strive to keep the scope of shared pointers as narrow as possible. This will ensure that they are released as soon as they are no longer needed.

Beware of circular references

Circular references occur when a group of shared pointers form a loop. Each shared pointer references the next one, and the last shared pointer in the loop goes back to the first one. This leads to a closed circle of references, where the reference count never goes to 0. Consider the following example:

cpp

main

In the code above, we have three Node objects, which represent connected elements in a linked list. Each Node has a next member, which is a shared pointer pointing to the next element in the linked list.

When should you consider using shared pointers?

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

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

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