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
> {
16 MOZ_DECLARE_REFCOUNTED_TYPENAME(Foo
)
18 Foo() : mDead(false) {}
20 static int sNumDestroyed
;
31 int Foo::sNumDestroyed
;
33 struct Bar
: public Foo
{};
35 already_AddRefed
<Foo
> NewFoo() {
36 RefPtr
<Foo
> f(new Foo());
40 already_AddRefed
<Foo
> NewBar() {
41 RefPtr
<Bar
> bar
= new Bar();
45 void GetNewFoo(Foo
** aFoo
) {
47 // Kids, don't try this at home
51 void GetNewFoo(RefPtr
<Foo
>* aFoo
) { *aFoo
= new Bar(); }
53 already_AddRefed
<Foo
> GetNullFoo() { return 0; }
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
);
65 static_assert(std::is_same_v
<decltype(f1
), RefPtr
<Foo
>>);
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
);
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();
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;
125 condition
? mozilla::MakeRefPtr
<Bar
>() : mozilla::MakeRefPtr
<Foo
>();
127 MOZ_RELEASE_ASSERT(f
);