Skip to content

Commit ae57fa2

Browse files
authored
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.
1 parent 48b703b commit ae57fa2

File tree

2 files changed

+8
-11
lines changed

2 files changed

+8
-11
lines changed

ctl/shared_ptr.h

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -335,19 +335,17 @@ class shared_ptr
335335
return p;
336336
}
337337

338-
#if 0 // TODO(mrdomino): find a different way
339338
template<typename U>
340339
bool owner_before(const shared_ptr<U>& r) const noexcept
341340
{
342-
return p < r.p;
341+
return rc < r.rc;
343342
}
344343

345344
template<typename U>
346345
bool owner_before(const weak_ptr<U>& r) const noexcept
347346
{
348347
return !r.owner_before(*this);
349348
}
350-
#endif
351349

352350
private:
353351
template<typename U>
@@ -422,13 +420,13 @@ class weak_ptr
422420
template<typename U>
423421
bool owner_before(const weak_ptr<U>& r) const noexcept
424422
{
425-
return p < r.p;
423+
return rc < r.rc;
426424
}
427425

428426
template<typename U>
429427
bool owner_before(const shared_ptr<U>& r) const noexcept
430428
{
431-
return p < r.p;
429+
return rc < r.rc;
432430
}
433431

434432
private:

test/ctl/shared_ptr_test.cc

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ struct Derived : Base
6969
int
7070
main()
7171
{
72-
int a;
72+
int a, b;
7373

7474
{
7575
// Shouldn't cause memory leaks.
@@ -182,17 +182,16 @@ main()
182182
return 13;
183183
}
184184

185-
#if 0 // TODO(mrdomino): find a different way
186185
{
187-
// owner_before works across shared and weak pointers.
186+
// owner_before shows equivalence only for equivalent objects.
188187
shared_ptr<int> x(&a, CallG());
189188
shared_ptr<int> y(&b, CallG());
190-
if (!x.owner_before(y))
189+
shared_ptr<void> z(x, &b);
190+
if (z.owner_before(x) || x.owner_before(z))
191191
return 14;
192-
if (!x.owner_before(weak_ptr<int>(y)))
192+
if (!z.owner_before(y) && !y.owner_before(z))
193193
return 15;
194194
}
195-
#endif
196195

197196
{
198197
// Use counts work like you'd expect

0 commit comments

Comments
 (0)