Missing pair of overridden memory management operator `new` and `delete`CXX-W2036
When you overload an allocation function in a given scope, it is necessary to also overload the corresponding deallocation function in the same scope to properly deallocate dynamically allocated resources. Failure to do so may cause undefined behavior while managing memory during program execution. This is especially important if the allocation function uses user-defined heap management to perform its allocations.
For example, if you overload the new
operator in a given scope, then you should also overload the delete
operator in the same scope. Similarly, if you overload the new[]
operator in a given scope, then you should also overload the delete[]
operator in the same scope.
By doing so, you ensure that memory is properly allocated and deallocated during program execution. This helps prevent memory leaks and other issues that can arise when working with dynamically allocated memory.
Bad practice
class DifferentlyAlloced {
void *operator new(std::size_t size) noexcept(false) {
void *ptr = ::operator new(size);
// do more then just new...
return ptr;
}
};
Recommended
class DifferentlyAlloced {
void *operator new(std::size_t size) noexcept(false) {
void *ptr = ::operator new(size);
// do more then just new...
return ptr;
}
void operator delete(void *ptr, std::size_t size) noexcept {
// undo the things done in new after allocating the memory...
::operator delete(ptr);
}
};
### References
- [DCL54-CPP. Overload allocation and deallocation functions as a pair in the same scope](https://wiki.sei.cmu.edu/confluence/display/cplusplus/DCL54-CPP.+Overload+allocation+and+deallocation+functions+as+a+pair+in+the+same+scope)