Manage Allocated Memory with std::unique_ptr

Learn to manage allocated memory with std::unique_ptr.

We'll cover the following

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 we 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 we allocate memory with new and fail to free it with delete, we 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 for an object, that object's constructor is called. And when the object's destructor is called, the memory is automatically returned to the heap.

For example, when we create a new smart pointer with make_unique():

Get hands-on with 1400+ tech skills courses.