这里 operator new 的 static 是什么意思?如果我把它放在头文件中会发生什么?
static void* operator new(size_t size, std::string s)
{
return 0;
}
int main()
{
return 0;
}
此代码在 visual studio 2013 上编译
但是gcc报错
error: 'void* operator new(size_t)' may not be declared as static
static void* operator new(size_t size)
clang也是如此
error: static declaration of 'operator new' follows non-static declaration
static void* operator new(size_t size)
这是 c++ 中的灰色地带,还是 visual studio 很慷慨?
最佳答案
static
对全局 operator new
没有用。 VS C++ 编译器很慷慨:void *operator new
已经声明为非静态的,不能第二次声明为静态的,GCC 和 clang 会通知您。
static
适用于类对象的重载自定义operator new
。 static
是必需的,因为 operator new 用于对象的分配并且 this
将在分配后首先可用,换句话说 operator new
首先返回 this
指针。
请注意,根据标准
15.5 Free store
Any allocation function for a class T is a static member (even if not explicitly declared static).
关于c++ - static for operator new 是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48944183/