This is the first of several posts I wrote related to smart pointers:
- Smart pointers
- unique_ptr
- More on unique_ptr
- shared_ptr
- weak_ptr
Memory management in C is error-prone because keeping track of every block of memory allocated and deallocated can be confusing and stressful.
Although C++ has the same manual memory management as C, it provides additional features that make memory management easier:
- When an object is instantiated on the stack (e.g., Object o;), the C++ runtime ensures that the object’s destructor is invoked when the object goes out of scope (when the end of the enclosing block is reached, a premature ‘return’ is encountered, or an exception is thrown), thereby releasing all memory and resources allocated for that object. This very nice feature is called RAII.
- (Ab)using the feature of operator overloading, we can create classes that simulate pointer behaviour. These classes are called: Smart pointers.