Operator new 在哪里以及如何实施?

CPP*_*PPL 7 c++ new-operator

这可能是一个愚蠢的问题,因为我对 C++ 中运算符的实现还很陌生......

我使用new运算符/表达式/关键字已经有一段时间了。但我刚刚注意到有一个名为 的函数operator new。据我所知,在大多数情况下,new操作符首先调用“默认”operator new为需要创建的对象分配原始内存,然后调用对象的构造函数在该内存上创建对象。我们可以operator new在全局范围或类中覆盖默认值。

我想知道(默认)operator new是在哪里定义的。一方面,我认为它没有在 中定义std,因为如果我这样做:

std::operator new(42);
Run Code Online (Sandbox Code Playgroud)

视觉工作室说namespace "std" has no member "operator new"。此外,operator new(42);当我既不包含任何标准标头也不包含using namespace std;.

另一方面,我发现如果我这样做:

include <iostream>
int main() { operator new(42); }
Run Code Online (Sandbox Code Playgroud)

Visual Studio 然后告诉我operator new我正在使用的内容如下:

_NODISCARD _Ret_notnull_ _Post_writable_byte_size_(_Size) _VCRT_ALLOCATOR
void* __CRTDECL operator new(
    size_t _Size
    );
Run Code Online (Sandbox Code Playgroud)

它在vcruntime_new.h( 又由included <new>) 中声明。然而,如果我注释掉include <iostream>,Visual Studio 会告诉我我正在使用以下内容:

void *operator new(unsigned long long)
Run Code Online (Sandbox Code Playgroud)

哪个is not located in a source code file.

所以我认为operator new与标准库有关。谁能澄清在operator new这些情况下实际发生了什么?

我感到困惑的另一件事是,如果程序以某种方式包含vcruntime_new.h,那么我可能会猜测编译器认为void* __CRTDECL operator new是在全局范围内。现在,如果我们在全局范围内定义自己的void* operator new(std::size_t);,编译器将选择使用operator new我们定义的而不是 中定义的vcruntime_new.h,并且不会产生歧义。请问这是如何实现的?