Why is quot;operator voidquot; not invoked with cast syntax?(为什么“操作员无效?不使用强制转换语法调用?)
问题描述
在玩 this answer 由 user GMan 我制作了以下代码段(使用 Visual C++ 9 编译):>
While playing with this answer by user GMan I crafted the following snippet (compiled with Visual C++ 9):
class Class {
public:
operator void() {}
};
Class object;
static_cast<void>( object );
(void)object;
object.operator void();
在调试器完成后,我发现强制转换为 void 不会调用 Class::operator void(),只有第三次调用(显式调用操作符) 实际上调用了操作符,这两个强制转换什么都不做.
after stepping over with the debugger I found out that casting to void doesn't invoke Class::operator void(), only the third invokation (with explicitly invoking the operator) actually invokes the operator, the two casts just do nothing.
为什么不使用强制转换语法调用 operator void?
Why is the operator void not invoked with the cast syntax?
推荐答案
技术原因见§12.3.2:
The technical reason why is found in §12.3.2:
从不使用转换函数将(可能有 cv 限定的)对象转换为(可能有 cv 限定的)相同对象类型(或对它的引用),再到该对象的(可能有 cv 限定的)基类类型(或对它的引用),或(可能是 cv 限定的)void.
A conversion function is never used to convert a (possibly cv-qualified) object to the (possibly cv-qualified) same object type (or a reference to it), to a (possibly cv-qualified) base class of that type (or a reference to it), or to (possibly cv-qualified) void.
理由是(可能)允许 §5.2.9/4 工作:
The rationale is (likely) to allow §5.2.9/4 to work:
任何表达式都可以显式转换为cv void"类型.表达式值被丢弃.
Any expression can be explicitly converted to type "cv void." The expression value is discarded.
(void)expr 假设对 any 表达式的结果值不做任何事情,但如果它调用您的转换运算符,它不会丢弃任何内容.所以他们禁止在转换中使用 operator void.
(void)expr to suppose to do nothing for the resulting value of any expression, but if it called your conversion operator it wouldn't be discarding anything. So they ban the use of operator void in conversions.
为什么不让转换类型 ID 为 void 使其格式错误?谁知道,但请记住,这并非完全没用:
Why not make it ill-formed to have the conversion-type-id be void? Who knows, but keep in mind it's not totally useless:
struct foo
{
operator void()
{
std::cout << "huh?" << std::endl;
}
};
typedef void (foo::*void_function)();
foo f;
void_function func = &foo::operator void;
(f.*func)(); // prints "huh"
f.operator void(); // also does (which you knew)
它在技术上对某事仍有潜在的用处,所以也许这足以让它不格式错误.
It is still technically potentially useful for something, so maybe that's rationale enough not to make it ill-formed.
这篇关于为什么“操作员无效"?不使用强制转换语法调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么“操作员无效"?不使用强制转换语法调用?
基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
