MEM51-CPP. Properly deallocate dynamically allocated resources
The C programming language provides several ways to allocate memory, such as std::malloc() , std::calloc() , and std::realloc() , which can be used by a C++ program. However, the C programming language defines only a single way to free the allocated memory: std::free() . See MEM31-C. Free dynamically allocated memory when no longer needed and MEM34-C. Only free memory allocated dynamically for rules specifically regarding C allocation and deallocation requirements.
The C++ programming language adds additional ways to allocate memory, such as the operators new , new[] , and placement new , and allocator objects . Unlike C, C++ provides multiple ways to free dynamically allocated memory, such as the operators delete , delete[]() , and deallocation functions on allocator objects.
Do not call a deallocation function on anything other than nullptr , or a pointer returned by the corresponding allocation function described by the following.
| Allocator | Deallocator |
|---|---|
global operator new()/new | global operator delete () /delete |
global operator new[]()/new[] | global operator delete[]()/delete[] |
class-specific operator new()/new | class-specific operator delete () /delete |
class-specific operator new[]()/new[] | class-specific operator delete[]()/delete[] |
placement operator new () | N/A |
allocator<T>::allocate() | allocator<T>::deallocate() |
std::malloc() , std::calloc() , std:: realloc() | std:: free() |
std::get_temporary |