1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "mozilla/RefPtr.h"
8 #include "mozilla/ThreadSafeWeakPtr.h"
10 using mozilla::SupportsThreadSafeWeakPtr
;
11 using mozilla::ThreadSafeWeakPtr
;
13 // To have a class C support weak pointers, inherit from
14 // SupportsThreadSafeWeakPtr<C>.
15 class C
: public SupportsThreadSafeWeakPtr
<C
> {
17 MOZ_DECLARE_THREADSAFEWEAKREFERENCE_TYPENAME(C
)
18 MOZ_DECLARE_REFCOUNTED_TYPENAME(C
)
25 // Setting mNum in the destructor allows us to test against use-after-free
35 MOZ_RELEASE_ASSERT(c1
->mNum
== 0);
37 // Get weak pointers to c1. The first time,
38 // a reference-counted ThreadSafeWeakReference object is created that
39 // can live beyond the lifetime of 'c1'. The ThreadSafeWeakReference
40 // object will be notified of 'c1's destruction.
41 ThreadSafeWeakPtr
<C
> w1(c1
);
44 // Test a weak pointer for validity before using it.
45 MOZ_RELEASE_ASSERT(s1
);
46 MOZ_RELEASE_ASSERT(s1
== c1
);
51 // Test taking another ThreadSafeWeakPtr<C> to c1
52 ThreadSafeWeakPtr
<C
> w2(c1
);
55 MOZ_RELEASE_ASSERT(s2
);
56 MOZ_RELEASE_ASSERT(s2
== c1
);
57 MOZ_RELEASE_ASSERT(w1
== s2
);
58 MOZ_RELEASE_ASSERT(s2
->mNum
== 1);
61 // Test that when a ThreadSafeWeakPtr is destroyed, it does not destroy the
62 // object that it points to, and it does not affect other ThreadSafeWeakPtrs
63 // pointing to the same object (e.g. it does not destroy the
64 // ThreadSafeWeakReference object).
66 ThreadSafeWeakPtr
<C
> w4local(c1
);
67 MOZ_RELEASE_ASSERT(w4local
== c1
);
69 // Now w4local has gone out of scope. If that had destroyed c1, then the
70 // following would fail for sure (see C::~C()).
71 MOZ_RELEASE_ASSERT(c1
->mNum
== 1);
72 // Check that w4local going out of scope hasn't affected other
73 // ThreadSafeWeakPtr's pointing to c1
74 MOZ_RELEASE_ASSERT(w1
== c1
);
75 MOZ_RELEASE_ASSERT(w2
== c1
);
77 // Now construct another C object and test changing what object a
78 // ThreadSafeWeakPtr points to
83 MOZ_RELEASE_ASSERT(s2
->mNum
== 1); // w2 was pointing to c1
88 MOZ_RELEASE_ASSERT(s2
);
89 MOZ_RELEASE_ASSERT(s2
== c2
);
90 MOZ_RELEASE_ASSERT(s2
!= c1
);
91 MOZ_RELEASE_ASSERT(w1
!= s2
);
92 MOZ_RELEASE_ASSERT(s2
->mNum
== 2);
95 // Destroying the underlying object clears weak pointers to it.
96 // It should not affect pointers that are not currently pointing to it.
99 !bool(w1
), "Deleting an object should clear ThreadSafeWeakPtr's to it.");
100 MOZ_RELEASE_ASSERT(bool(w2
),
101 "Deleting an object should not clear ThreadSafeWeakPtr "
102 "that are not pointing to it.");
106 !bool(w2
), "Deleting an object should clear ThreadSafeWeakPtr's to it.");