C++/CLI equivalent of C# checked keyword

2019-04-13 01:50发布

问题:

Is there a way for managed code in C++/CLI to throw exceptions on arithmetic overflow? C# has the checked keyword and also global project flags to enable these, but I can find neither in C++/CLI...

My situation is that I am wrapping C++ libs in .NET. Sometimes the C++ native code overflows. I was/am considering moving some sensitive calculations to existing C++/CLI wrapper, but perhaps this is not possible?

回答1:

The linked duplicate make no sense, C++/CLI follows C++ conventions. C++ has no built-in mechanism for detecting arithmetic overflow.

Using the checked and unchecked keywords was originally planned for future extensions of C++/CLI. Ecma-372 is the current language standard and proposes this extension in appendix F.2.1. This however never happened and is very unlikely to be ever implemented.

You'll thus have to implement overflow checking yourself. You'll find some guidance in this question.