|
1 /* This Source Code Form is subject to the terms of the Mozilla Public |
|
2 * License, v. 2.0. If a copy of the MPL was not distributed with this |
|
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
|
4 |
|
5 #include "mozilla/WeakPtr.h" |
|
6 |
|
7 using mozilla::SupportsWeakPtr; |
|
8 using mozilla::WeakPtr; |
|
9 |
|
10 // To have a class C support weak pointers, inherit from SupportsWeakPtr<C>. |
|
11 class C : public SupportsWeakPtr<C> |
|
12 { |
|
13 public: |
|
14 MOZ_DECLARE_REFCOUNTED_TYPENAME(C) |
|
15 int num; |
|
16 void act() {} |
|
17 }; |
|
18 |
|
19 static void |
|
20 Example() |
|
21 { |
|
22 |
|
23 C* ptr = new C(); |
|
24 |
|
25 // Get weak pointers to ptr. The first time asWeakPtr is called |
|
26 // a reference counted WeakReference object is created that |
|
27 // can live beyond the lifetime of 'ptr'. The WeakReference |
|
28 // object will be notified of 'ptr's destruction. |
|
29 WeakPtr<C> weak = ptr->asWeakPtr(); |
|
30 WeakPtr<C> other = ptr->asWeakPtr(); |
|
31 |
|
32 // Test a weak pointer for validity before using it. |
|
33 if (weak) { |
|
34 weak->num = 17; |
|
35 weak->act(); |
|
36 } |
|
37 |
|
38 // Destroying the underlying object clears weak pointers to it. |
|
39 delete ptr; |
|
40 |
|
41 MOZ_RELEASE_ASSERT(!weak, "Deleting |ptr| clears weak pointers to it."); |
|
42 MOZ_RELEASE_ASSERT(!other, "Deleting |ptr| clears all weak pointers to it."); |
|
43 } |
|
44 |
|
45 struct A : public SupportsWeakPtr<A> |
|
46 { |
|
47 MOZ_DECLARE_REFCOUNTED_TYPENAME(A) |
|
48 int data; |
|
49 }; |
|
50 |
|
51 |
|
52 int |
|
53 main() |
|
54 { |
|
55 |
|
56 A* a = new A; |
|
57 |
|
58 // a2 is unused to test the case when we haven't initialized |
|
59 // the internal WeakReference pointer. |
|
60 A* a2 = new A; |
|
61 |
|
62 a->data = 5; |
|
63 WeakPtr<A> ptr = a->asWeakPtr(); |
|
64 { |
|
65 WeakPtr<A> ptr2 = a->asWeakPtr(); |
|
66 MOZ_RELEASE_ASSERT(ptr->data == 5); |
|
67 WeakPtr<A> ptr3 = a->asWeakPtr(); |
|
68 MOZ_RELEASE_ASSERT(ptr->data == 5); |
|
69 } |
|
70 |
|
71 delete a; |
|
72 MOZ_RELEASE_ASSERT(!ptr); |
|
73 |
|
74 delete a2; |
|
75 |
|
76 Example(); |
|
77 |
|
78 return 0; |
|
79 } |