问题
I'm looking to avoid an overflow in managed C++ (CLI). In C# there is an unchecked keyword, and in C++ overflows do not end up in exceptions.
For reference, unchecked is documented here. Basically if you do:
unchecked
{
int1 = 2147483647 + 10; //this overflows in CLI but is ok in C# and C++
}
In C# it will not overflow but convert to int by taking the least significant bits. This is appropriate when you compute hash codes for example.
Note: I realize there is no equivalent C++ keyword, but some bit shifting should do the trick;
回答1:
You can just use #pragma unmanaged
around a method to get the normal unchecked behavior in native C++.
回答2:
Use an unsigned data type for bit operations and checksumming. Wrap-around behavior of unsigned behavior is well-defined in C++.
来源:https://stackoverflow.com/questions/14500593/what-is-the-c-equivalent-of-the-c-sharp-checked