Fix shared_ptr::owner_before (#1274)

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.
This commit is contained in:
Steven Dee (Jōshin) 2024-09-01 17:34:39 -04:00 committed by GitHub
parent 48b703b3f6
commit ae57fa2c4e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 8 additions and 11 deletions

View file

@ -335,11 +335,10 @@ class shared_ptr
return p; return p;
} }
#if 0 // TODO(mrdomino): find a different way
template<typename U> template<typename U>
bool owner_before(const shared_ptr<U>& r) const noexcept bool owner_before(const shared_ptr<U>& r) const noexcept
{ {
return p < r.p; return rc < r.rc;
} }
template<typename U> template<typename U>
@ -347,7 +346,6 @@ class shared_ptr
{ {
return !r.owner_before(*this); return !r.owner_before(*this);
} }
#endif
private: private:
template<typename U> template<typename U>
@ -422,13 +420,13 @@ class weak_ptr
template<typename U> template<typename U>
bool owner_before(const weak_ptr<U>& r) const noexcept bool owner_before(const weak_ptr<U>& r) const noexcept
{ {
return p < r.p; return rc < r.rc;
} }
template<typename U> template<typename U>
bool owner_before(const shared_ptr<U>& r) const noexcept bool owner_before(const shared_ptr<U>& r) const noexcept
{ {
return p < r.p; return rc < r.rc;
} }
private: private:

View file

@ -69,7 +69,7 @@ struct Derived : Base
int int
main() main()
{ {
int a; int a, b;
{ {
// Shouldn't cause memory leaks. // Shouldn't cause memory leaks.
@ -182,17 +182,16 @@ main()
return 13; 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<int> x(&a, CallG()); shared_ptr<int> x(&a, CallG());
shared_ptr<int> y(&b, CallG()); shared_ptr<int> y(&b, CallG());
if (!x.owner_before(y)) shared_ptr<void> z(x, &b);
if (z.owner_before(x) || x.owner_before(z))
return 14; return 14;
if (!x.owner_before(weak_ptr<int>(y))) if (!z.owner_before(y) && !y.owner_before(z))
return 15; return 15;
} }
#endif
{ {
// Use counts work like you'd expect // Use counts work like you'd expect