命名空间内的 new 运算符
namespace X
{
void* operator new (size_t);
}
给出错误消息为:
error: ‘void* X::operator new(size_t)’ may not be declared within a namespace
是否是 gcc 编译器错误 ?在旧的 gcc 版本中它似乎可以工作。 知道吗,为什么不允许?
用例: 我只想允许类自定义operator new/delete
,并希望禁止全局new/operator
。很容易捕获编译器错误,而不是链接器错误;所以我编码:
namespace X {
void* operator new (size_t);
}
using namespace X;
这适用于旧版本的 gcc,但不适用于新版本。
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 ? In older gcc version it seems to be working.
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
. Instead of linker error, it was easy to catch compiler error; 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是不允许的,因为它没有意义。例如
,现在您有以下内容:
ptr
应该如何delete
d - 使用全局命名空间operator delete()
或特定于代码>命名空间X? C++ 无法推断出这一点。
This is not allowed because it makes no sense. For example you have the following
now how should the
ptr
bedelete
d - with global namespaceoperator delete()
or with the one specific tonamespace X
? There's no possible way for C++ to deduce that.如果我们从标准中考虑这一部分,@Sharptooth 的答案更有意义:
3.7.3.1 分配函数 [basic.stc.dynamic.allocation]
上述限制可能是由于 @sharptooth 的回答指出的原因而施加的。
@Sharptooth's Answer makes more sense if we consider this section from the standard:
3.7.3.1 Allocation functions [basic.stc.dynamic.allocation]
The above limitation is probably imposed for the very reason that @sharptooth's answer points out.