From fcf3fe37c60afb8ce480e4cfeaf1924c8c85ea42 Mon Sep 17 00:00:00 2001 From: maflcko <6399679+maflcko@users.noreply.github.com> Date: Mon, 23 Mar 2026 19:18:30 +0100 Subject: [PATCH] gsl::not_null: C.89: Make a hash noexcept (#1236) 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())), | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Co-authored-by: MarcoFalke <*~=`'#}+{/-|&$^_@721217.xyz> --- 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 c6a5ae8..436f09a 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 6e72bf7..fcee2ed 100644 --- a/tests/pointers_tests.cpp +++ b/tests/pointers_tests.cpp @@ -2,6 +2,7 @@ #include +#include #include #include #include @@ -98,4 +99,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