In C ++ global operator new: why it can be replaced

I wrote a small program in VS2005 to check if the C ++ global operator new can be overloaded. He 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;
}

      

The above title is calling my definition of the new operator. If I remove this function from the code, the new operator is called in C: \ Program Files (x86) \ Microsoft Visual Studio 8 \ VC \ crt \ src \ new.cpp.

Things are good. However, in my opinion my implementations of the new operator DO NOT overload new in new.cpp, it DOES NOT SUBJECT with it and violates the single definition rule. Why doesn't the compiler complain about this? Or does the standard say that because the new operator is so special, one definition rule doesn't apply here?

Thanks.

+2


a source to share


1 answer


Yes, global operator new

is special in that programs can provide a replacement for it.



Replaceable shapes are single object and array shapes operator new

and operator delete

and "no throw" options. Other forms, such as the placement of new ones, are not replaced.

+7


a source







All Articles