History of the Question:
Regular (raw) pointers are the traditional mechanism in C++ for working with dynamic memory. This is a universal abstract mechanism, but unfortunately, it is very prone to errors: memory leaks, double deletions, and dangling pointer issues. Therefore, starting with C++11, the standard library includes smart pointers — template classes (std::unique_ptr, std::shared_ptr, std::weak_ptr) that automatically manage the lifetime of the object.
The Problem:
When using regular pointers, the responsibility for allocating and freeing memory falls on the programmer. Errors in memory deallocation lead to leaks, data corruption, and crashes. Particularly complex cases arise in exception handling or when passing pointers to other functions.
The Solution:
Smart pointers encapsulate allocated memory and automatically free it when there are no more owners. They implement RAII. std::unique_ptr provides exclusive ownership, std::shared_ptr allows shared ownership, and std::weak_ptr provides non-owning references (to prevent "circular references").
Code Example:
#include <memory> void foo() { std::unique_ptr<int> p = std::make_unique<int>(5); // memory will be freed even on exception // ... }
Key Features:
Can std::unique_ptr be used with an array created with new[]?
No, for arrays use std::unique_ptr<T[]>: this will call delete[] instead of delete.
std::unique_ptr<int[]> arr(new int[10]);
Can standard smart pointers prevent all possible memory leaks?
No. For example, cyclic references between std::shared_ptr will lead to leaks. To break such cycles, std::weak_ptr is used.
Can smart pointers "delete" the same object twice?
No, unless ownership logic is violated (i.e., raw pointers are used!). If a raw pointer is copied manually, destruction could happen twice.
Raw pointers are used, memory is freed manually, and memory is not freed upon throwing an exception.
Pros:
Cons:
std::unique_ptr and std::make_unique are used to create objects and pass them to functions.
Pros:
Cons: