An In-Depth Look at Dynamic Allocation

In this chapter, you will learn how to work with dynamic memory allocation. This chapter is important because not all variables can be defined globally or on the stack (that is, from within a function), as global memory should be avoided where possible and stack memory is usually far more limited than heap memory (the memory that's used for dynamic memory allocations). The use of heap memory, however, has lead to numerous bugs over the years with respect to leaking and dangling pointers.

This chapter will teach you not only how this dynamic memory allocation works but also how to allocate memory from the heap correctly in a C++ Core Guideline compliant manner.

Beginning with why we use smart pointers as well as the difference between them, conversions, and other references, we will conclude this chapter with a brief explanation of how the heap works under Linux and why dynamic memory allocation is so slow.

In this chapter, we will cover the following recipes:

  • Comparing std::shared_ptr and std::unique_ptr
  • Converting from a unique_ptr into a shared_ptr
  • Working with circular references
  • Typecasting with smart pointers
  • The heap under a microscope

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset