From dc1820955ff897bc619aeb258d5d5b88020b8193 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Steven=20Dee=20=28J=C5=8Dshin=29?= Date: Sun, 1 Sep 2024 14:15:58 -0700 Subject: [PATCH] Fix shared_ptr::owner_before This method is supposed to give equivalence iff two shared pointers both own the same object, even if they point to different addresses. We can't control the exact order of the control blocks in memory, so the test can only check that this equivalence/non-equivalence relationship holds, and this is in fact all that it should check. --- ctl/shared_ptr.h | 8 +++----- test/ctl/shared_ptr_test.cc | 11 +++++------ 2 files changed, 8 insertions(+), 11 deletions(-) diff --git a/ctl/shared_ptr.h b/ctl/shared_ptr.h index 019d6fb29..ae3316831 100644 --- a/ctl/shared_ptr.h +++ b/ctl/shared_ptr.h @@ -335,11 +335,10 @@ class shared_ptr return p; } -#if 0 // TODO(mrdomino): find a different way template bool owner_before(const shared_ptr& r) const noexcept { - return p < r.p; + return rc < r.rc; } template @@ -347,7 +346,6 @@ class shared_ptr { return !r.owner_before(*this); } -#endif private: template @@ -422,13 +420,13 @@ class weak_ptr template bool owner_before(const weak_ptr& r) const noexcept { - return p < r.p; + return rc < r.rc; } template bool owner_before(const shared_ptr& r) const noexcept { - return p < r.p; + return rc < r.rc; } private: diff --git a/test/ctl/shared_ptr_test.cc b/test/ctl/shared_ptr_test.cc index 27dd0b76c..960d6b5fc 100644 --- a/test/ctl/shared_ptr_test.cc +++ b/test/ctl/shared_ptr_test.cc @@ -69,7 +69,7 @@ struct Derived : Base int main() { - int a; + int a, b; { // Shouldn't cause memory leaks. @@ -182,17 +182,16 @@ main() return 13; } -#if 0 // TODO(mrdomino): find a different way { - // owner_before works across shared and weak pointers. + // owner_before shows equivalence only for equivalent objects. shared_ptr x(&a, CallG()); shared_ptr y(&b, CallG()); - if (!x.owner_before(y)) + shared_ptr z(x, &b); + if (z.owner_before(x) || x.owner_before(z)) return 14; - if (!x.owner_before(weak_ptr(y))) + if (!z.owner_before(y) && !y.owner_before(z)) return 15; } -#endif { // Use counts work like you'd expect