Manage allocated memory with std::unique_ptr
Smart pointers are an excellent tool for managing allocated heap memory.
Heap memory is managed at the lowest level by the C functions, malloc()
and free()
. malloc()
allocates a block of memory from the heap, and free()
returns it to the heap. These functions do not perform initialization and do not call constructors or destructors. If you fail to return allocated memory to the heap with a call to free()
, the behavior is undefined and often leads to memory leaks and security vulnerabilities.
C++ provides the new
and delete
operators to allocate and free heap memory, in place of malloc()
and free()
. The new
and delete
operators call object constructors and destructors but still do not manage memory. If you allocate memory with new
and fail to free it with delete
, you will leak memory.
Introduced with C++14, smart pointers comply with the Resource Acquisition Is Initialization (RAII) idiom. This means that when memory is allocated...