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
> {
13 friend class base::RefCounted
<SelfAssign
>;
18 class CheckDerivedMemberAccess
: public scoped_refptr
<SelfAssign
> {
20 CheckDerivedMemberAccess() {
21 // This shouldn't compile if we don't have access to the member variable.
22 SelfAssign
** pptr
= &ptr_
;
23 EXPECT_EQ(*pptr
, ptr_
);
27 class ScopedRefPtrToSelf
: public base::RefCounted
<ScopedRefPtrToSelf
> {
29 ScopedRefPtrToSelf() : self_ptr_(this) {}
31 static bool was_destroyed() { return was_destroyed_
; }
33 void SelfDestruct() { self_ptr_
= NULL
; }
36 friend class base::RefCounted
<ScopedRefPtrToSelf
>;
37 ~ScopedRefPtrToSelf() { was_destroyed_
= true; }
39 static bool was_destroyed_
;
41 scoped_refptr
<ScopedRefPtrToSelf
> self_ptr_
;
44 bool ScopedRefPtrToSelf::was_destroyed_
= false;
48 TEST(RefCountedUnitTest
, TestSelfAssignment
) {
49 SelfAssign
* p
= new SelfAssign
;
50 scoped_refptr
<SelfAssign
> var(p
);
52 EXPECT_EQ(var
.get(), p
);
55 TEST(RefCountedUnitTest
, ScopedRefPtrMemberAccess
) {
56 CheckDerivedMemberAccess check
;
59 TEST(RefCountedUnitTest
, ScopedRefPtrToSelf
) {
60 ScopedRefPtrToSelf
* check
= new ScopedRefPtrToSelf();
61 EXPECT_FALSE(ScopedRefPtrToSelf::was_destroyed());
62 check
->SelfDestruct();
63 EXPECT_TRUE(ScopedRefPtrToSelf::was_destroyed());
66 TEST(RefCountedUnitTest
, ScopedRefPtrToOpaque
) {
67 scoped_refptr
<base::OpaqueRefCounted
> p
= base::MakeOpaqueRefCounted();
68 base::TestOpaqueRefCounted(p
);
70 scoped_refptr
<base::OpaqueRefCounted
> q
;
72 base::TestOpaqueRefCounted(p
);
73 base::TestOpaqueRefCounted(q
);