On C++ global operator new: why it can be replaced
- by Jimmy
I wrote a small program in VS2005 to test whether C++ global operator new can be overloaded. It can.
#include "stdafx.h"
#include "iostream"
#include "iomanip"
#include "string"
#include "new"
using namespace std;
class C {
public:
C() { cout<<"CTOR"<<endl; }
};
void * operator new(size_t size)
{
cout<<"my overload of global plain old new"<<endl;
// try to allocate size bytes
void *p = malloc(size);
return (p);
}
int main() {
C* pc1 = new C;
cin.get();
return 0;
}
In the above, my definition of operator new is called. If I remove that function from the code, then operator new in C:\Program Files (x86)\Microsoft Visual Studio 8\VC\crt\src\new.cpp gets called.
All is good. However, in my opinion, my implementations of operator new does NOT overload the new in new.cpp, it CONFLICTS with it and violates the one-definition rule. Why doesn't the compiler complain about it? Or does the standard say since operator new is so special, one-definition rule does not apply here?
Thanks.