Fri, 16 Jan 2015 18:13:44 +0100
Integrate suggestion from review to improve consistency with existing code.
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/. */
5 #include "mozilla/WeakPtr.h"
7 using mozilla::SupportsWeakPtr;
8 using mozilla::WeakPtr;
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 };
19 static void
20 Example()
21 {
23 C* ptr = new C();
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();
32 // Test a weak pointer for validity before using it.
33 if (weak) {
34 weak->num = 17;
35 weak->act();
36 }
38 // Destroying the underlying object clears weak pointers to it.
39 delete ptr;
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 }
45 struct A : public SupportsWeakPtr<A>
46 {
47 MOZ_DECLARE_REFCOUNTED_TYPENAME(A)
48 int data;
49 };
52 int
53 main()
54 {
56 A* a = new A;
58 // a2 is unused to test the case when we haven't initialized
59 // the internal WeakReference pointer.
60 A* a2 = new A;
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 }
71 delete a;
72 MOZ_RELEASE_ASSERT(!ptr);
74 delete a2;
76 Example();
78 return 0;
79 }