在玩 this answer 时通过 user GMan我制作了以下代码片段(使用 Visual C++ 9 编译):
class Class {
public:
operator void() {}
};
Class object;
static_cast<void>( object );
(void)object;
object.operator void();
通过调试器后,我发现转换为 void
不会调用 Class::operator void()
,只有第三次调用(显式调用运算符)实际上调用了运算符,这两个转换什么都不做。
为什么 operator void
没有用强制转换语法调用?
最佳答案
在 §12.3.2 中找到的技术原因:
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 工作:
Any expression can be explicitly converted to type “cv void.” The expression value is discarded.
(void)expr
假设对 any 表达式的结果值不做任何事情,但如果它调用你的转换运算符,它就不会丢弃任何东西。所以他们禁止在转换中使用 operator void
。
为什么不使转换类型 ID 为 void
格式错误?谁知道呢,但请记住它并非完全没用:
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)
它在技术上仍然对某些东西有用,所以也许这足以使它的格式不正确。
关于c++ - 为什么不使用强制转换语法调用 "operator void"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30532566/