c++ - static for operator new 是什么意思

标签 c++

这里 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 很慷慨?

代码链接:https://www.ideone.com/kZmWgf

最佳答案

static 对全局 operator new 没有用。 VS C++ 编译器很慷慨:void *operator new 已经声明为非静态的,不能第二次声明为静态的,GCC 和 clang 会通知您。

static 适用于类对象的重载自定义operator newstatic 是必需的,因为 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/

相关文章:

c++ - 需要空终止的 string_view

c++ - 包含的 C++/C 头文件的实现在哪里?

c++ - Logitech Quickcam Pro 9000 Bayer 使用 openCV 进行捕捉

c++ - 打破 int 和 float 之间严格别名的实际后果

c++ - 命名空间与头文件

c++ - 多重继承 : same variable name

c++ - 了解模板内定义的模板 (C++)

C++继承虚函数

c++ - 从 vector 范围中删除特定元素

c++ - 为什么我必须通过this指针访问模板基类成员?