1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/memory/ref_counted.h"
7 #include "base/test/opaque_ref_counted.h"
8 #include "testing/gtest/include/gtest/gtest.h"
12 class SelfAssign
: public base::RefCounted
<SelfAssign
> {
14 virtual ~SelfAssign() {}
17 friend class base::RefCounted
<SelfAssign
>;
20 class Derived
: public SelfAssign
{
22 ~Derived() override
{}
25 friend class base::RefCounted
<Derived
>;
28 class CheckDerivedMemberAccess
: public scoped_refptr
<SelfAssign
> {
30 CheckDerivedMemberAccess() {
31 // This shouldn't compile if we don't have access to the member variable.
32 SelfAssign
** pptr
= &ptr_
;
33 EXPECT_EQ(*pptr
, ptr_
);
37 class ScopedRefPtrToSelf
: public base::RefCounted
<ScopedRefPtrToSelf
> {
39 ScopedRefPtrToSelf() : self_ptr_(this) {}
41 static bool was_destroyed() { return was_destroyed_
; }
43 void SelfDestruct() { self_ptr_
= NULL
; }
46 friend class base::RefCounted
<ScopedRefPtrToSelf
>;
47 ~ScopedRefPtrToSelf() { was_destroyed_
= true; }
49 static bool was_destroyed_
;
51 scoped_refptr
<ScopedRefPtrToSelf
> self_ptr_
;
54 bool ScopedRefPtrToSelf::was_destroyed_
= false;
58 TEST(RefCountedUnitTest
, TestSelfAssignment
) {
59 SelfAssign
* p
= new SelfAssign
;
60 scoped_refptr
<SelfAssign
> var(p
);
62 EXPECT_EQ(var
.get(), p
);
65 TEST(RefCountedUnitTest
, ScopedRefPtrMemberAccess
) {
66 CheckDerivedMemberAccess check
;
69 TEST(RefCountedUnitTest
, ScopedRefPtrToSelf
) {
70 ScopedRefPtrToSelf
* check
= new ScopedRefPtrToSelf();
71 EXPECT_FALSE(ScopedRefPtrToSelf::was_destroyed());
72 check
->SelfDestruct();
73 EXPECT_TRUE(ScopedRefPtrToSelf::was_destroyed());
76 TEST(RefCountedUnitTest
, ScopedRefPtrToOpaque
) {
77 scoped_refptr
<base::OpaqueRefCounted
> p
= base::MakeOpaqueRefCounted();
78 base::TestOpaqueRefCounted(p
);
80 scoped_refptr
<base::OpaqueRefCounted
> q
;
82 base::TestOpaqueRefCounted(p
);
83 base::TestOpaqueRefCounted(q
);
86 TEST(RefCountedUnitTest
, BooleanTesting
) {
87 scoped_refptr
<SelfAssign
> p
;
93 TEST(RefCountedUnitTest
, Equality
) {
94 scoped_refptr
<SelfAssign
> p1(new SelfAssign
);
95 scoped_refptr
<SelfAssign
> p2(new SelfAssign
);
104 TEST(RefCountedUnitTest
, ConvertibleEquality
) {
105 scoped_refptr
<Derived
> p1(new Derived
);
106 scoped_refptr
<SelfAssign
> p2
;