operator new inside namespace(命名空间内的运算符 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,但不适用于新版本.
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.
这篇关于命名空间内的运算符 new的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:命名空间内的运算符 new
基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
