Where and how is operator new implemented?

Viewed 122

This may be a silly question as I'm quite new to the implementations of operators in C++...

I've been using the new operator/expression/keyword for a while. But I've just noticed that there is a function called operator new. As far as I know, in most cases, the new operator calls the "default" operator new first to allocate raw memory for the object it is required to create, and then calls the constructor of the object to create the object on that memory. And we're allowed to override the default operator new both in global scope or in a class.

I wonder where the (default) operator new is defined. On one hand, I don't think it is defined in std, because if I do:

std::operator new(42);

Visual studio says namespace "std" has no member "operator new". Moreover, operator new(42); runs successfully when I'm neither including any standard header nor using namespace std;.

On the other hand, I found that if I do:

include <iostream>
int main() { operator new(42); }

Visual Studio then tells me that the operator new I am using is something as follows:

_NODISCARD _Ret_notnull_ _Post_writable_byte_size_(_Size) _VCRT_ALLOCATOR
void* __CRTDECL operator new(
    size_t _Size
    );

which is declared in vcruntime_new.h (which is in turn included by <new>). Whereas if I comment out include <iostream>, Visual Studio tells me that I am using something as:

void *operator new(unsigned long long)

which is not located in a source code file.

So I think operator new has something to do with the standard library. Could anyone please clarify on what actually happens to operator new in those situations?

Another thing that I am confusing about is that if the program somehow includes vcruntime_new.h, then I may guess that the compiler sees void* __CRTDECL operator new to be in global scope. Now, if we define our own void* operator new(std::size_t); in global scope, the compiler will choose to use the operator new defined by us instead of the one defined in vcruntime_new.h, and there is no ambiguity. May I ask how this is achieved?

0 Answers
Related