运算符new内部命名空间

编程入门 行业动态 更新时间:2024-10-26 12:29:18
本文介绍了运算符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内部命名空间

本文发布于:2023-11-05 19:22:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1561640.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:运算符   空间

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!