1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/mfbt/tests/TestWeakPtr.cpp Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,79 @@ 1.4 +/* This Source Code Form is subject to the terms of the Mozilla Public 1.5 + * License, v. 2.0. If a copy of the MPL was not distributed with this 1.6 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 1.7 + 1.8 +#include "mozilla/WeakPtr.h" 1.9 + 1.10 +using mozilla::SupportsWeakPtr; 1.11 +using mozilla::WeakPtr; 1.12 + 1.13 +// To have a class C support weak pointers, inherit from SupportsWeakPtr<C>. 1.14 +class C : public SupportsWeakPtr<C> 1.15 +{ 1.16 + public: 1.17 + MOZ_DECLARE_REFCOUNTED_TYPENAME(C) 1.18 + int num; 1.19 + void act() {} 1.20 +}; 1.21 + 1.22 +static void 1.23 +Example() 1.24 +{ 1.25 + 1.26 + C* ptr = new C(); 1.27 + 1.28 + // Get weak pointers to ptr. The first time asWeakPtr is called 1.29 + // a reference counted WeakReference object is created that 1.30 + // can live beyond the lifetime of 'ptr'. The WeakReference 1.31 + // object will be notified of 'ptr's destruction. 1.32 + WeakPtr<C> weak = ptr->asWeakPtr(); 1.33 + WeakPtr<C> other = ptr->asWeakPtr(); 1.34 + 1.35 + // Test a weak pointer for validity before using it. 1.36 + if (weak) { 1.37 + weak->num = 17; 1.38 + weak->act(); 1.39 + } 1.40 + 1.41 + // Destroying the underlying object clears weak pointers to it. 1.42 + delete ptr; 1.43 + 1.44 + MOZ_RELEASE_ASSERT(!weak, "Deleting |ptr| clears weak pointers to it."); 1.45 + MOZ_RELEASE_ASSERT(!other, "Deleting |ptr| clears all weak pointers to it."); 1.46 +} 1.47 + 1.48 +struct A : public SupportsWeakPtr<A> 1.49 +{ 1.50 + MOZ_DECLARE_REFCOUNTED_TYPENAME(A) 1.51 + int data; 1.52 +}; 1.53 + 1.54 + 1.55 +int 1.56 +main() 1.57 +{ 1.58 + 1.59 + A* a = new A; 1.60 + 1.61 + // a2 is unused to test the case when we haven't initialized 1.62 + // the internal WeakReference pointer. 1.63 + A* a2 = new A; 1.64 + 1.65 + a->data = 5; 1.66 + WeakPtr<A> ptr = a->asWeakPtr(); 1.67 + { 1.68 + WeakPtr<A> ptr2 = a->asWeakPtr(); 1.69 + MOZ_RELEASE_ASSERT(ptr->data == 5); 1.70 + WeakPtr<A> ptr3 = a->asWeakPtr(); 1.71 + MOZ_RELEASE_ASSERT(ptr->data == 5); 1.72 + } 1.73 + 1.74 + delete a; 1.75 + MOZ_RELEASE_ASSERT(!ptr); 1.76 + 1.77 + delete a2; 1.78 + 1.79 + Example(); 1.80 + 1.81 + return 0; 1.82 +}