Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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.

Any explanation for this design decision?

like image 857
Vincent Avatar asked Jul 18 '26 13:07

Vincent


2 Answers

bool b = true;
b = ~b;

The value of b after this operation is 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.

So it has to provide an operator so that the result is how you would expect it.

like image 64
Neil Kirk Avatar answered Jul 21 '26 03:07

Neil Kirk


Thanks to the integral promotions, ~true is ~1, which is most assuredly nonzero, and hence not false, when converted back to bool.

like image 29
T.C. Avatar answered Jul 21 '26 02:07

T.C.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!