Chapter 12. Memory Management with std::unique_ptr
This chapter shows you how to work effectively with objects on the heap to ensure that memory is released when you’ve finished with it.
You met char pointers in Chapter 9 and saw more details on the std::string in Chapter 11.
The std::string provides a higher level of abstraction than char pointers, making your life easier.
Like the std::vector, the std::string resizes for you, and both tidy up when they go out of scope, so you don’t need to do it yourself.
C++ provides other features to help you clean up when you’re done with an object.
If you do want cleanup objects allocated on the heap, you can avoid the low-level, manual manage memory by using a smart pointer: a type that works like a pointer but tidies up for you.
There are several types of smart pointer, so let’s start with the easiest to use.
You will then be able to extend your trading game in Chapter 13 using a smart pointer.
So why would you want to use the heap?
So far, you haven’t needed to do this directly yourself, even though std::string and std::vector might use the heap in the background.
Chapter 13 will show you an important use case for heap objects: allowing behavior to vary with class type.
Another use case is for objects that change size.
Many objects have a fixed size, such as integers.
In contrast, the std::vector and std::string can both contain varying numbers of elements, so use the heap to allocate dynamically when you don’t know the required size ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access