为什么“操作员无效"?不使用强制转换语法调用? [英] Why is "operator void" not invoked with cast syntax?

查看:19
本文介绍了为什么“操作员无效"?不使用强制转换语法调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在玩 this answeruser 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.

这篇关于为什么“操作员无效"?不使用强制转换语法调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆