From 590917330e8e074a3144668ff751878c0487db46 Mon Sep 17 00:00:00 2001 From: MarcoFalke <*~=`'#}+{/-|&$^_@721217.xyz> Date: Mon, 23 Mar 2026 07:48:51 +0100 Subject: [PATCH] gsl::not_null: C.89: Make a hash noexcept Without this change, the guideline https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#c89-make-a-hash-noexcept would be violated. The test fails before the changes here: ``` tests/pointers_tests.cpp:102:23: error: static assertion failed due to requirement 'noexcept(std::hash>>{}(std::declval()))': gsl::not_null hash operator must be noexcept 102 | static_assert(noexcept(std::hash{}(std::declval())), | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ tests/pointers_tests.cpp:108:23: error: static assertion failed due to requirement 'noexcept(std::hash>>{}(std::declval()))': gsl::strict_not_null hash operator must be noexcept 108 | static_assert(noexcept(std::hash{}(std::declval())), | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --- include/gsl/pointers | 2 +- tests/pointers_tests.cpp | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/include/gsl/pointers b/include/gsl/pointers index d73dc05de..409053c20 100644 --- a/include/gsl/pointers +++ b/include/gsl/pointers @@ -235,7 +235,7 @@ not_null operator+(std::ptrdiff_t, const not_null&) = delete; template >::value> struct not_null_hash { - std::size_t operator()(const T& value) const { return std::hash{}(value.get()); } + std::size_t operator()(const T& value) const noexcept { return std::hash{}(value.get()); } }; template diff --git a/tests/pointers_tests.cpp b/tests/pointers_tests.cpp index 729cc5f0d..3532e0580 100644 --- a/tests/pointers_tests.cpp +++ b/tests/pointers_tests.cpp @@ -2,6 +2,7 @@ #include +#include #include #include #include @@ -94,4 +95,19 @@ TEST(pointers_test, member_types) "check member type: element_type"); } +TEST(pointers_test, hash_noexcept_compiles) +{ + { + using Key = gsl::not_null>; + static_assert(noexcept(std::hash{}(std::declval())), + "gsl::not_null hash operator must be noexcept"); + } + + { + using Key = gsl::strict_not_null>; + static_assert(noexcept(std::hash{}(std::declval())), + "gsl::strict_not_null hash operator must be noexcept"); + } +} + } // namespace