运算符new内部命名空间 [英] operator new inside namespace

查看:145
本文介绍了运算符new内部命名空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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,但不适用于新版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内部命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆