C & C++

C & C++

Made by DeepSource

Missing pair of overridden memory management operator new and delete CXX-W2036

Bug risk
Minor

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

```cpp 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