b2gdroid confvars.sh change for 2.5 merge r+a=me
[gecko.git] / mfbt / tests / TestRefPtr.cpp
blob4d9e712bd360603378388b2156912d8caeca463d
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 file,
5 * You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "mozilla/RefPtr.h"
8 #include "mozilla/RefCounted.h"
10 using mozilla::RefCounted;
12 class Foo : public RefCounted<Foo>
14 public:
15 MOZ_DECLARE_REFCOUNTED_TYPENAME(Foo)
17 Foo() : mDead(false) {}
19 static int sNumDestroyed;
21 ~Foo()
23 MOZ_ASSERT(!mDead);
24 mDead = true;
25 sNumDestroyed++;
28 private:
29 bool mDead;
31 int Foo::sNumDestroyed;
33 struct Bar : public Foo {};
35 already_AddRefed<Foo>
36 NewFoo()
38 RefPtr<Foo> f(new Foo());
39 return f.forget();
42 already_AddRefed<Foo>
43 NewBar()
45 RefPtr<Bar> bar = new Bar();
46 return bar.forget();
49 void
50 GetNewFoo(Foo** aFoo)
52 *aFoo = new Bar();
53 // Kids, don't try this at home
54 (*aFoo)->AddRef();
57 void
58 GetNewFoo(RefPtr<Foo>* aFoo)
60 *aFoo = new Bar();
63 already_AddRefed<Foo>
64 GetNullFoo()
66 return 0;
69 int
70 main()
72 MOZ_RELEASE_ASSERT(0 == Foo::sNumDestroyed);
74 RefPtr<Foo> f = new Foo();
75 MOZ_RELEASE_ASSERT(f->refCount() == 1);
77 MOZ_RELEASE_ASSERT(1 == Foo::sNumDestroyed);
80 RefPtr<Foo> f1 = NewFoo();
81 RefPtr<Foo> f2(NewFoo());
82 MOZ_RELEASE_ASSERT(1 == Foo::sNumDestroyed);
84 MOZ_RELEASE_ASSERT(3 == Foo::sNumDestroyed);
87 RefPtr<Foo> b = NewBar();
88 MOZ_RELEASE_ASSERT(3 == Foo::sNumDestroyed);
90 MOZ_RELEASE_ASSERT(4 == Foo::sNumDestroyed);
93 RefPtr<Foo> f1;
95 f1 = new Foo();
96 RefPtr<Foo> f2(f1);
97 RefPtr<Foo> f3 = f2;
98 MOZ_RELEASE_ASSERT(4 == Foo::sNumDestroyed);
100 MOZ_RELEASE_ASSERT(4 == Foo::sNumDestroyed);
102 MOZ_RELEASE_ASSERT(5 == Foo::sNumDestroyed);
106 RefPtr<Foo> f = new Foo();
107 RefPtr<Foo> g = f.forget();
109 MOZ_RELEASE_ASSERT(6 == Foo::sNumDestroyed);
113 RefPtr<Foo> f = new Foo();
114 GetNewFoo(getter_AddRefs(f));
115 MOZ_RELEASE_ASSERT(7 == Foo::sNumDestroyed);
117 MOZ_RELEASE_ASSERT(8 == Foo::sNumDestroyed);
120 RefPtr<Foo> f = new Foo();
121 GetNewFoo(&f);
122 MOZ_RELEASE_ASSERT(9 == Foo::sNumDestroyed);
124 MOZ_RELEASE_ASSERT(10 == Foo::sNumDestroyed);
127 RefPtr<Foo> f1 = new Bar();
129 MOZ_RELEASE_ASSERT(11 == Foo::sNumDestroyed);
132 RefPtr<Foo> f = GetNullFoo();
133 MOZ_RELEASE_ASSERT(11 == Foo::sNumDestroyed);
135 MOZ_RELEASE_ASSERT(11 == Foo::sNumDestroyed);
137 return 0;