Safe Narrowing Conversion Support in the GSL

Let’s briefly introduce a generic helper function from the Guidelines Support Library (GSL), that checks narrowing conversions and throws an exception on errors.

In the previous blog post on conversions from size_t to int and related bugs, we saw some custom code that checked that the conversion from the input size_t value to int was safe, and in case it wasn’t, an exception was thrown. Of course, you can customize that code to throw your own custom exception class, or maybe assert in debug builds and throw an exception in release builds, log the error, etc.

In addition to that, the Microsoft’s implementation of the GSL library offers a utility function called gsl::narrow<T>, that checks if the input argument can be represented in the target type T, and if it cannot, the function throws an exception of type gsl::narrowing_error. The implementation code of that function is more generic than the specific case discussed in the previous blog post, but requires that you use the GSL library (in general not a problem, if your C++ compiler supports it), and that the specific gsl::narrowing_error is thrown. Of course you can pick whatever fits your needs best (maybe using that GSL function fits your needs, or maybe you want a different behavior when an unsafe conversion is encountered, so you need to write your own custom code).