51 Memory Allocation
51 Memory Allocation
In this lesson, we will learn about an important subsection of memory management, i.e., memory allocation.
• Introduction
• Memory allocation
• new
• new[]
• Placement new
• Typical use-cases
• Failed allocation
• New handler
• Further information
Introduction #
Explicit memory management in C++ has a high complexity but also provides
us with great functionality. Sadly, this special domain of C++ is not so well
known.
We can use the operators new and new[] to allocate memory and the
operators delete and delete[] to deallocate memory.
The compiler manages its memory automatically on the stack.
Memory allocation #
new #
Thanks to the new operator, we can dynamically allocate memory for the
instance of a type.
new[] #
The default constructor will be invoked for each element of the C array.
The STL Containers and the C++ String automatically manage their
memory.
Placement new #
Placement new is often used to instantiate an object or a C array in a specific
area of memory. In addition, we can overload placement new globally or for
our own data types. This is a big benefit offered by C++.
Typical use-cases #
Explicit memory allocation
Avoidance of exceptions
Debugging
Failed allocation #
If the memory allocation operation fails, new and new[] will raise a
std::bad_alloc exception. But that is not the behavior we want. Therefore, we
can invoke placement new with the constant std::nothrow . This call will
return a nullptr in the case of failure.
New handler #
In the case of a failed allocation, we can use std::set_new_handler with our
own handler. std::set_new_handler returns the older handler and needs a
callable unit. A callable unit is typically a function, a function object, or a
lambda-function. The callable unit should take no arguments and return
nothing. We can get the handler currently being used by invoking the function
std::get_new_handler .
Further information #
Smart pointers