简体   繁体   English

为什么std :: bitset :: reference :: operator~?

[英]Why std::bitset::reference::operator~?

I was reading the documentation of std::bitset and I was wondering why std::bitset::reference explicitly define operator~ because I don't see any performance or design reasons. 我正在阅读std::bitset文档 ,我想知道为什么std::bitset::reference显式定义operator~因为我没有看到任何性能或设计原因。 Without it, I think it would work equally well: 没有它,我认为它同样有效:

bool b = ~mybitset[i];

because the reference would be converted to a bool, on which the ~ operator would be applied. 因为引用将转换为bool,将在其上应用~运算符。

Any explanation for this design decision? 对此设计决定有何解释?

bool b = true;
b = ~b;

The value of b after this operation is true ! 此操作后b的值为true

This is because ~ promotes the bool to int of value 1, then performs the bitwise-not on the result, which resolves to -2, and then casts that back to bool which is true. 这是因为~bool提升为值为1的int ,然后对结果执行bitwise-not,结果为-2,然后将其转换回bool ,这是真的。

So it has to provide an operator so that the result is how you would expect it. 所以它必须提供一个操作员,以便结果是你所期望的。

由于积分促销, ~true ~1 ,当转换回bool时,这肯定是非零的,因此不是false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM