Using unique_ptr to uniquely own a memory resource
Manual handling of heap memory allocation and releasing it is one of the most controversial features of C++. All allocations must be properly paired with a corresponding delete operation in the correct scope. If the memory allocation is done in a function and needs to be released before the function returns, for instance, then this has to happen on all the return paths, including the abnormal situation where a function returns because of an exception. C++11 features, such as rvalues and move semantics, have enabled the development of smart pointers; these pointers can manage a memory resource and automatically release it when the smart pointer is destroyed. In this recipe, we will look at
std::unique_ptr, a smart pointer that owns and manages another object or an array of objects allocated on the heap, and performs the disposal operation when the smart pointer goes out of scope.
In the following examples...