C++ memory Library
C++ memory Classes and Functions
The <memory> library has smart pointers. A smart pointer works like a normal pointer, but it frees the memory automatically when it is no longer used, so you do not need delete.
A list of the most common classes and functions in the <memory> library can be found in the tables below.
Smart Pointer Classes
| Name | Description |
|---|---|
| unique_ptr | A smart pointer that is the only owner of its memory |
| shared_ptr | A smart pointer that can share its memory with other shared_ptr variables |
| weak_ptr | A pointer that watches the memory of a shared_ptr, without being an owner |
Functions
| Name | Description |
|---|---|
| make_shared() | Creates a value in new memory, and returns a shared_ptr that points to it |
Smart Pointer Methods
| Name | Description |
|---|---|
| get() | Returns the normal (raw) pointer that a smart pointer holds |
| reset() | Frees the memory of a smart pointer, and optionally makes it point to new memory |
| release() | Gives up the ownership of a unique_ptr, and returns the normal pointer |
| use_count() | Returns the number of shared_ptr variables that own the same memory |
| lock() | Returns a shared_ptr to the memory that a weak_ptr watches |
| expired() | Checks if the memory that a weak_ptr watches is already freed |
Other Classes and Functions
The <memory> library also has these. They are used in more advanced code:
| Name | Description |
|---|---|
| make_unique() | Creates a unique_ptr. It was added in C++14. In C++11, write unique_ptr<int> ptr(new int(25)); instead |
| allocator | A class that gets and frees memory for containers, like vector |
| get_deleter() | Returns the custom deleter (the function that frees the memory) of a smart pointer |
| enable_shared_from_this | A base class that lets an object create a shared_ptr that points to itself |