Reputation: 373
I'm working on a legacy C product that has lots of castings and potential losses of data - casting from int to short kind of stuff. In Visual Studio, is there a way to cause an exception if this loss of data happens, or do I need to fill my code with asserts?
Upvotes: 1
Views: 87
Reputation: 6578
C++ does not have in language features to support throwing exceptions on lossy conversions. If you use brace initialization, as of C++11, the compiler is required to let you know about possibly-narrowing conversions, but that doesn't mean a conversion is narrowing in practice (i.e. at runtime).
The best solution to something like this is to either write your own library to do this, or to use one that already exists, such as SafeInt.
Upvotes: 3