From 596f1ee227773e56f26a68c506132261d3bbf3a4 Mon Sep 17 00:00:00 2001 From: bgloyer <36457894+bgloyer@users.noreply.github.com> Date: Thu, 30 Sep 2021 11:05:14 -0700 Subject: [PATCH] ES.46 Issue 1797 - narrowing to bool (#1824) * ES.46 Issue 1797 * spacing * remove spaces * dereference ptr * spacing * used contextual conversions to bool wording --- CppCoreGuidelines.md | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/CppCoreGuidelines.md b/CppCoreGuidelines.md index 14618a0..844648e 100644 --- a/CppCoreGuidelines.md +++ b/CppCoreGuidelines.md @@ -11704,17 +11704,24 @@ A key example is basic narrowing: The guidelines support library offers a `narrow_cast` operation for specifying that narrowing is acceptable and a `narrow` ("narrow if") that throws an exception if a narrowing would throw away legal values: - i = narrow_cast(d); // OK (you asked for it): narrowing: i becomes 7 - i = narrow(d); // OK: throws narrowing_error + i = gsl::narrow_cast(d); // OK (you asked for it): narrowing: i becomes 7 + i = gsl::narrow(d); // OK: throws narrowing_error We also include lossy arithmetic casts, such as from a negative floating point type to an unsigned integral type: double d = -7.9; unsigned u = 0; - u = d; // BAD - u = narrow_cast(d); // OK (you asked for it): u becomes 4294967289 - u = narrow(d); // OK: throws narrowing_error + u = d; // bad: narrowing + u = gsl::narrow_cast(d); // OK (you asked for it): u becomes 4294967289 + u = gsl::narrow(d); // OK: throws narrowing_error + +##### Note + +This rule does not apply to [contextual conversions to bool](https://en.cppreference.com/w/cpp/language/implicit_conversion#Contextual_conversions): + + if (ptr) do_something(*ptr); // OK: ptr is used as a condition + bool b = ptr; // bad: narrowing ##### Enforcement