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

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

bookApplication For Unique Pointers

Unique pointers offer a safe way to initialize scope-limited heap memory. Here are a few scenarios in which unique pointers are well-suited:

  • as a golden rule, define all pointers as unique pointers, unless they have to be shared. This ensures a lower overall memory footprint of your application, as unique pointers don’t count references;
  • use unique pointers when dealing with heap memory that should be allocated when entering a scope, and deallocated when exiting the scope. For example, you can use a unique pointer for creating a large vector of temporary, dynamic objects inside a function;
  • you can also use unique pointers to manage resources like file handles, sockets, and database connections. They ensure that the pointed resource is released when the pointer goes out of scope, reducing chances of resource leaks;
  • unique pointers are also a good fit when creating complex data structures like trees or doubly linked lists. By enforcing single ownership of each element in the structure, they can simplify memory and code management.

When not to use unique pointers

However, there are certain scenarios where unique pointers are not the best choice. Let’s look at a few:

  • i f your program requires multiple pointers to share the ownership of a resource, then you can’t use a unique pointer;
  • if you want multiple parts of your program to access a shared resource, you shouldn’t use a unique pointer to manage that resource. While it may be possible to pass around the raw pointer (of a unique pointer) to different parts of your code, it would break the core principle of unique ownership and potentially lead to memory leaks/corruption;
  • if you are working with legacy code or third-party packages that don’t support smart pointers, you may have to rely on raw pointers, or other ways to manage memory.
The following code compiles and runs fine. Analyze it carefully. Is using a `unique_ptr` for the `Resource` object the right decision?

The following code compiles and runs fine. Analyze it carefully. Is using a unique_ptr for the Resource object the right decision?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 3
some-alt