【问题标题】:What does static for operator new mean运算符 new 的静态是什么意思
【发布时间】:2018-08-03 07:02:21
【问题描述】:

这里的 operator new 的 static 是什么意思?如果我把它放在头文件中会发生什么?

static void* operator new(size_t size, std::string s)
{
    return 0;
}

int main() 
{
    return 0;
}

此代码在 Visual Studio 2013 上编译

但是 gcc 报错

错误:'void* operator new(size_t)' 可能未声明 作为静态的

static void* operator new(size_t size)

叮当声也是这样

错误:'operator new' 的静态声明遵循非静态 声明

static void* operator new(size_t size)

这是 C++ 中的灰色地带,还是 Visual Studio 大方?

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

【问题讨论】:

  • VS 很慷慨。
  • static 对于类级别的自定义分配函数是强制性的,但如果它是全局分配函数,则没有任何意义。
  • VS 并不慷慨:“错误 C2323:'operator new':非成员 operator new 或 delete 函数不得声明为静态或在全局命名空间以外的命名空间中”。你的 VS 版本太旧了。将运算符替换为一个源代码文件而不是另一个源代码文件通常效果不佳。所以你最好把它修好。
  • @Hans Passant 请务必提及 vs 的版本
  • 从 VS2017 版本 15.5.6 得到的

标签: c++


【解决方案1】:

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

static 适用于类对象的重载自定义operator newstatic 是必需的,因为运算符 new 用于分配对象,this 将在分配后首先可用,换句话说,operator new 首先返回 this 指针。

请注意,根据标准

15.5 免费商店

类 T 的任何分配函数都是静态成员(即使不是 显式声明为静态)。

【讨论】:

    猜你喜欢
    • 2010-10-26
    • 2013-05-07
    • 2015-09-18
    • 2017-03-29
    • 2011-03-16
    • 2011-07-09
    • 2016-07-23
    • 1970-01-01
    相关资源
    最近更新 更多