简体   繁体   English

命名空间内的新运算符

[英]operator new inside namespace

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

gives error message as:给出错误信息:

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

Is it a gcc compiler bug ?它是gcc 编译器错误吗? In older gcc version it seems to be working.在较旧的 gcc 版本中,它似乎可以正常工作。 Any idea, why it's not allowed?任何想法,为什么不允许?

Use case : I wanted to allow only custom operator new/delete for the classes and wanted to disallow global new/operator .用例:我想只允许类的自定义operator new/delete并希望禁止全局new/operator Instead of linker error, it was easy to catch compiler error;而不是 linker 错误,很容易捕获编译器错误; so I coded:所以我编码:

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

This worked for older version of gcc but not for the new one.这适用于旧版本的 gcc 但不适用于新版本。

This is not allowed because it makes no sense.这是不允许的,因为它没有任何意义。 For example you have the following例如你有以下

int* ptr = 0;

namespace X {
    void* operator new (size_t);
    void operator delete(void*);
    void f()
    {
       ptr = new int();
    }
}

void f()
{
    delete ptr;
    ptr = 0;
}

now how should the ptr be delete d - with global namespace operator delete() or with the one specific to namespace X ?现在应该如何delete ptr - 使用全局命名空间operator delete()或使用特定于namespace X的一个? There's no possible way for C++ to deduce that. C++ 无法推断出这一点。

@Sharptooth's Answer makes more sense if we consider this section from the standard:如果我们从标准中考虑这一部分,@Sharptooth 的答案会更有意义:

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

[..] An allocation function shall be a class member function or a global function; [..] 分配 function 应为 class 成员 function 或全局 ZC1C425Z068E68385D1CAB41 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. 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. [..] [..]

The above limitation is probably imposed for the very reason that @sharptooth's answer points out.上述限制可能是由于@sharptooth 的回答指出的原因而施加的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM