Smart pointers are objects that manage dynamic memory automatically, ensuring proper resource release and preventing memory leaks.
They are defined in the header:
Problems with raw pointers:
Memory leaks
Dangling pointers
Double deletion
Smart pointers solve these using RAII (Resource Acquisition Is Initialization).
C++ provides three main smart pointers:
unique_ptr
shared_ptr
weak_ptr
unique_ptrOwns the memory exclusively
Cannot be copied
Can be moved
Lightweight
Fast
Automatically deletes memory
shared_ptrMultiple pointers share ownership
Uses reference counting
Memory freed when count becomes zero
Safe shared ownership
Slight overhead due to reference counting
weak_ptrDoes not own the object
Prevents circular references
Used with shared_ptr
| Feature | unique_ptr | shared_ptr | weak_ptr |
|---|---|---|---|
| Ownership | Single | Multiple | None |
| Copyable | No | Yes | Yes |
| Reference count | No | Yes | No |
| Memory overhead | Low | Medium | Low |
| Use case | Exclusive ownership | Shared resources | Breaking cycles |
Used when memory needs special cleanup.
| Raw Pointer | Smart Pointer |
|---|---|
| Manual memory control | Automatic memory control |
| Error-prone | Safe |
| No ownership concept | Clear ownership |
Prefer make_unique and make_shared
Use unique_ptr by default
Use shared_ptr only when sharing is required
Use weak_ptr to avoid circular dependencies
Avoid mixing raw and smart pointers
Smart pointers follow RAII
Prevent memory leaks
Improve code safety and clarity
Essential in modern C++
Smart pointers are a core feature of modern C++ that provide safe, automatic, and efficient memory management.
Take quizzes related to this topic and see where you stand!
Start Quiz Now