michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: #include "mozilla/WeakPtr.h" michael@0: michael@0: using mozilla::SupportsWeakPtr; michael@0: using mozilla::WeakPtr; michael@0: michael@0: // To have a class C support weak pointers, inherit from SupportsWeakPtr. michael@0: class C : public SupportsWeakPtr michael@0: { michael@0: public: michael@0: MOZ_DECLARE_REFCOUNTED_TYPENAME(C) michael@0: int num; michael@0: void act() {} michael@0: }; michael@0: michael@0: static void michael@0: Example() michael@0: { michael@0: michael@0: C* ptr = new C(); michael@0: michael@0: // Get weak pointers to ptr. The first time asWeakPtr is called michael@0: // a reference counted WeakReference object is created that michael@0: // can live beyond the lifetime of 'ptr'. The WeakReference michael@0: // object will be notified of 'ptr's destruction. michael@0: WeakPtr weak = ptr->asWeakPtr(); michael@0: WeakPtr other = ptr->asWeakPtr(); michael@0: michael@0: // Test a weak pointer for validity before using it. michael@0: if (weak) { michael@0: weak->num = 17; michael@0: weak->act(); michael@0: } michael@0: michael@0: // Destroying the underlying object clears weak pointers to it. michael@0: delete ptr; michael@0: michael@0: MOZ_RELEASE_ASSERT(!weak, "Deleting |ptr| clears weak pointers to it."); michael@0: MOZ_RELEASE_ASSERT(!other, "Deleting |ptr| clears all weak pointers to it."); michael@0: } michael@0: michael@0: struct A : public SupportsWeakPtr michael@0: { michael@0: MOZ_DECLARE_REFCOUNTED_TYPENAME(A) michael@0: int data; michael@0: }; michael@0: michael@0: michael@0: int michael@0: main() michael@0: { michael@0: michael@0: A* a = new A; michael@0: michael@0: // a2 is unused to test the case when we haven't initialized michael@0: // the internal WeakReference pointer. michael@0: A* a2 = new A; michael@0: michael@0: a->data = 5; michael@0: WeakPtr ptr = a->asWeakPtr(); michael@0: { michael@0: WeakPtr ptr2 = a->asWeakPtr(); michael@0: MOZ_RELEASE_ASSERT(ptr->data == 5); michael@0: WeakPtr ptr3 = a->asWeakPtr(); michael@0: MOZ_RELEASE_ASSERT(ptr->data == 5); michael@0: } michael@0: michael@0: delete a; michael@0: MOZ_RELEASE_ASSERT(!ptr); michael@0: michael@0: delete a2; michael@0: michael@0: Example(); michael@0: michael@0: return 0; michael@0: }