Learning when to use unique_ptr, and the implications for size

In the previous recipe, we've learned the two fundamental ways of managing memory in C++: automatic and dynamic. We've also learned that dynamic memory is available to the developer in a greater quantity compared to automatic memory (that is, available from the stack), and offers great flexibility. On the other hand dealing with dynamic memory can be an unpleasant experience:

  • The pointer does not indicate whether it points to an array or to a single object.
  • When freeing the allocated memory, you don't know if you have to use delete or delete[], so you have to look at how the variable is defined.
  • There is no explicit way to tell if the pointer is dangling.

These are just a few issues you might encounter when dealing with dynamic memory, and then, with new and delete. unique_ptr is a smart pointer, which means that it knows when the memory should be deallocated, removing the burden from the developer. In this recipe, you'll learn how to use unique_ptr and make_unique properly.