Merge mozilla-central to autoland. a=merge CLOSED TREE
[gecko.git] / mfbt / tests / TestRefPtr.cpp
blob972e284c441ed503afee596fa44d80ef6bf5a50a
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 #include <type_traits>
12 using mozilla::RefCounted;
14 class Foo : public RefCounted<Foo> {
15 public:
16 MOZ_DECLARE_REFCOUNTED_TYPENAME(Foo)
18 Foo() : mDead(false) {}
20 static int sNumDestroyed;
22 ~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> NewFoo() {
36 RefPtr<Foo> f(new Foo());
37 return f.forget();
40 already_AddRefed<Foo> NewBar() {
41 RefPtr<Bar> bar = new Bar();
42 return bar.forget();
45 void GetNewFoo(Foo** aFoo) {
46 *aFoo = new Bar();
47 // Kids, don't try this at home
48 (*aFoo)->AddRef();
51 void GetNewFoo(RefPtr<Foo>* aFoo) { *aFoo = new Bar(); }
53 already_AddRefed<Foo> GetNullFoo() { return 0; }
55 int main() {
56 MOZ_RELEASE_ASSERT(0 == Foo::sNumDestroyed);
58 RefPtr<Foo> f = new Foo();
59 MOZ_RELEASE_ASSERT(f->refCount() == 1);
61 MOZ_RELEASE_ASSERT(1 == Foo::sNumDestroyed);
64 RefPtr f1 = NewFoo();
65 static_assert(std::is_same_v<decltype(f1), RefPtr<Foo>>);
66 RefPtr f2(NewFoo());
67 static_assert(std::is_same_v<decltype(f2), RefPtr<Foo>>);
68 MOZ_RELEASE_ASSERT(1 == Foo::sNumDestroyed);
70 MOZ_RELEASE_ASSERT(3 == Foo::sNumDestroyed);
73 RefPtr<Foo> b = NewBar();
74 MOZ_RELEASE_ASSERT(3 == Foo::sNumDestroyed);
76 MOZ_RELEASE_ASSERT(4 == Foo::sNumDestroyed);
79 RefPtr<Foo> f1;
81 f1 = new Foo();
82 RefPtr<Foo> f2(f1);
83 RefPtr<Foo> f3 = f2;
84 MOZ_RELEASE_ASSERT(4 == Foo::sNumDestroyed);
86 MOZ_RELEASE_ASSERT(4 == Foo::sNumDestroyed);
88 MOZ_RELEASE_ASSERT(5 == Foo::sNumDestroyed);
92 RefPtr<Foo> f = new Foo();
93 RefPtr<Foo> g = f.forget();
95 MOZ_RELEASE_ASSERT(6 == Foo::sNumDestroyed);
99 RefPtr<Foo> f = new Foo();
100 GetNewFoo(getter_AddRefs(f));
101 MOZ_RELEASE_ASSERT(7 == Foo::sNumDestroyed);
103 MOZ_RELEASE_ASSERT(8 == Foo::sNumDestroyed);
106 RefPtr<Foo> f = new Foo();
107 GetNewFoo(&f);
108 MOZ_RELEASE_ASSERT(9 == Foo::sNumDestroyed);
110 MOZ_RELEASE_ASSERT(10 == Foo::sNumDestroyed);
112 { RefPtr<Foo> f1 = new Bar(); }
113 MOZ_RELEASE_ASSERT(11 == Foo::sNumDestroyed);
116 RefPtr f = GetNullFoo();
117 static_assert(std::is_same_v<decltype(f), RefPtr<Foo>>);
118 MOZ_RELEASE_ASSERT(11 == Foo::sNumDestroyed);
120 MOZ_RELEASE_ASSERT(11 == Foo::sNumDestroyed);
123 bool condition = true;
124 const auto f =
125 condition ? mozilla::MakeRefPtr<Bar>() : mozilla::MakeRefPtr<Foo>();
127 MOZ_RELEASE_ASSERT(f);
130 return 0;