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


基础教程推荐
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 从 std::cin 读取密码 2021-01-01