命名空间内的运算符 new

2022-01-14 00:00:00 namespaces c++ new-operator compiler-bug
namespace X
{
  void* operator new (size_t);
}

给出错误信息:

error: ‘void* X::operator new(size_t)’ may not be declared within a namespace

它是 gcc 编译器错误 吗?在较旧的 gcc 版本中,它似乎正在工作.任何想法,为什么不允许?

Is it a gcc compiler bug ? In older gcc version it seems to be working. Any idea, why it's not allowed ?

用例:我想只允许类的自定义 operator new/delete 并希望禁止全局 new/operator.不是链接器错误,而是很容易捕获编译器错误;所以我编码:

Use case: I wanted to allow only custom operator new/delete for the classes and wanted to disallow global new/operator. Instead of linker error, it was easy to catch compiler error; so I coded:

namespace X {
  void* operator new (size_t);
}
using namespace X;

这适用于旧版本的 gcc,但不适用于新版本.

This worked for older version of gcc but not for the new one.

推荐答案

如果我们从标准中考虑这一部分,@Sharptooth 的答案会更有意义:

@Sharptooth's Answer makes more sense if we consider this section from the standard:

3.7.3.1 分配函数[basic.stc.dynamic.allocation]

[..] 分配函数应该是类成员函数或全局函数;如果分配函数在全局范围以外的命名空间范围内声明或在全局范围内声明为静态,则程序是格式错误的.[..]

[..] An allocation function shall be a class member function or a global function; a program is ill-formed if an allocation function is declared in a namespace scope other than global scope or declared static in global scope. [..]

上述限制可能是出于@sharptooth 的回答所指出的原因.

The above limitation is probably imposed for the very reason that @sharptooth's answer points out.

相关文章