Smart Pointers
Smart pointers are objects that behave like raw pointers but automatically manage the lifetime of dynamically allocated memory.
<memory> library has three type of smart pointer:
- std::unique_ptr
- std::shared_ptr
- std::weak_ptr
std::unique_ptr
Only one owner, memory is deleted automatically when pointer goes out of scope
std::shared_ptr
Multiple owners, Internally uses a reference counter memory is deleted when counter reaches 0.
std::weak_ptr
Non-owning observer of a shared_ptr, does't increase reference count
TODO: explain usage and more
RAII
Resource Acquisition Is Initialization
A resource is acquired in the constructor and released in the destructor
Resource
A resource is anything that must be release manually
| Resource | Acquire | Release |
|---|---|---|
| heap memory | new |
delete |
| file | open() |
close() |
| mutex | lock() |
unlock() |
| socket | socket() |
close() |
| GPU memory | allocate | free |
Demo:
```cpp title="without RAII (memory leak) void example() { int* p = new int(5);
1 2 3 | |
}
cpp title="with RAII"
void example()
{
std::unique_ptr
Memory released when unique_ptr out of scope