C++ – Difference between operator new and operator new[]


I've overloaded the global operator new/delete/new[]/delete[] but simple tests show that while my versions of new and delete are being called correctly, doing simple array allocations and deletes with new[] and delete[] causes the implementations in newaop.cpp and delete2.cpp to be called.

For example, this code

int* a = new int[10];

calls operator new[] in newaop.cpp, which in turn calls my version of operator new. So it seems they are globally overloaded but for some reason not the array versions. Is there something I'm missing?

EDIT: My implementation of the operators are in a separate project which is compiled into a library and linked to statically. In retrospect, this might have been useful to include in the original post, as it probably has something to do with this. Although I still can't figure out why only the array versions are affected.

Best Solution

I don't know how you overloaded operator new[] but I just tried it with MSVC2008:

void* operator new[](size_t size)
  return 0;

int main()
  int* a = new int[5];

The code above effectively calls my faulty implementation of operator new[].

So here is my guess: you failed at overloading operator new[] for some reason and your program uses the compiler's version of operator new[] which relies on operator new to allocate the memory. Since you overloaded operator new, your implementation gets called.