Skip to content

Commit 1883887

Browse files
Fix std::hash compilation error for gsl::not_null<std::shared_ptr<T>> (#1210)
* Initial plan for issue * Fix hash compilation issue for gsl::not_null with shared_ptr Co-authored-by: carsonRadtke <[email protected]> * Add comment explaining safe usage of typename T::element_type in not_null_hash Co-authored-by: carsonRadtke <[email protected]> * Initial plan for issue * Remove upgrade_checklist.md file as requested Co-authored-by: carsonRadtke <[email protected]> * restore docs/upgrade_checklist.md --------- Co-authored-by: copilot-swe-agent[bot] <[email protected]> Co-authored-by: carsonRadtke <[email protected]> Co-authored-by: Carson Radtke <[email protected]>
1 parent c31617f commit 1883887

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

include/gsl/pointers

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -231,7 +231,8 @@ template <class T>
231231
not_null<T> operator+(std::ptrdiff_t, const not_null<T>&) = delete;
232232

233233

234-
template <class T, class U = decltype(std::declval<const T&>().get()), bool = std::is_default_constructible<std::hash<U>>::value>
234+
// T is conceptually a pointer so we don't have to worry about it being a reference and violating std::hash requirements
235+
template <class T, class U = typename T::element_type, bool = std::is_default_constructible<std::hash<U>>::value>
235236
struct not_null_hash
236237
{
237238
std::size_t operator()(const T& value) const { return std::hash<U>{}(value.get()); }

tests/notnull_tests.cpp

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -735,4 +735,18 @@ TEST(notnull_tests, TestStdHash)
735735
EXPECT_FALSE(hash_nn(nn) == hash_intptr(&y));
736736
EXPECT_FALSE(hash_nn(nn) == hash_intptr(nullptr));
737737
}
738+
739+
{
740+
auto x = std::make_shared<int>(42);
741+
auto y = std::make_shared<int>(99);
742+
not_null<std::shared_ptr<int>> nn{x};
743+
const not_null<std::shared_ptr<int>> cnn{x};
744+
745+
std::hash<not_null<std::shared_ptr<int>>> hash_nn;
746+
std::hash<std::shared_ptr<int>> hash_sharedptr;
747+
748+
EXPECT_TRUE(hash_nn(nn) == hash_sharedptr(x));
749+
EXPECT_FALSE(hash_nn(nn) == hash_sharedptr(y));
750+
EXPECT_TRUE(hash_nn(cnn) == hash_sharedptr(x));
751+
}
738752
}

0 commit comments

Comments
 (0)