给出错误消息为:
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,但不适用于新版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]
3.7.3.1 Allocation functions [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.
更多推荐
运算符new内部命名空间
发布评论