Skip to content

Commit 99a29ce

Browse files
Document safe usage of undefined behavior in gsl::narrow (microsoft#1024)
1 parent ebf0498 commit 99a29ce

File tree

1 file changed

+6
-1
lines changed

1 file changed

+6
-1
lines changed

include/gsl/narrow

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,12 @@ GSL_SUPPRESS(f.6) // NO-FORMAT: attribute // TODO: MSVC /analyze does not recogn
3636
constexpr const bool is_different_signedness =
3737
(std::is_signed<T>::value != std::is_signed<U>::value);
3838

39-
const T t = narrow_cast<T>(u);
39+
GSL_SUPPRESS(es.103) // NO-FORMAT: attribute // don't overflow
40+
GSL_SUPPRESS(es.104) // NO-FORMAT: attribute // don't underflow
41+
GSL_SUPPRESS(p.2) // NO-FORMAT: attribute // don't rely on undefined behavior
42+
const T t = narrow_cast<T>(u); // While this is technically undefined behavior in some cases (i.e., if the source value is of floating-point type
43+
// and cannot fit into the destination integral type), the resultant behavior is benign on the platforms
44+
// that we target (i.e., no hardware trap representations are hit).
4045

4146
if (static_cast<U>(t) != u || (is_different_signedness && ((t < T{}) != (u < U{}))))
4247
{

0 commit comments

Comments
 (0)