1 // Copyright 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 "skia/ext/refptr.h"
7 #include "testing/gtest/include/gtest/gtest.h"
12 TEST(RefPtrTest
, ReferenceCounting
) {
13 SkRefCnt
* ref
= new SkRefCnt();
14 EXPECT_TRUE(ref
->unique());
17 // Adopt the reference from the caller on creation.
18 RefPtr
<SkRefCnt
> refptr1
= AdoptRef(ref
);
19 EXPECT_TRUE(ref
->unique());
20 EXPECT_TRUE(refptr1
->unique());
22 EXPECT_EQ(ref
, &*refptr1
);
23 EXPECT_EQ(ref
, refptr1
.get());
26 // Take a second reference for the second instance.
27 RefPtr
<SkRefCnt
> refptr2(refptr1
);
28 EXPECT_FALSE(ref
->unique());
30 RefPtr
<SkRefCnt
> refptr3
;
31 EXPECT_FALSE(refptr3
);
33 // Take a third reference for the third instance.
35 EXPECT_FALSE(ref
->unique());
37 // Same object, so should have the same refcount.
39 EXPECT_FALSE(ref
->unique());
41 // Drop the object from refptr2, so it should lose its reference.
44 EXPECT_FALSE(ref
->unique());
46 EXPECT_FALSE(refptr2
);
47 EXPECT_EQ(NULL
, refptr2
.get());
50 EXPECT_FALSE(refptr3
->unique());
51 EXPECT_EQ(ref
, &*refptr3
);
52 EXPECT_EQ(ref
, refptr3
.get());
55 // Drop a reference when the third object is destroyed.
56 EXPECT_TRUE(ref
->unique());
60 TEST(RefPtrTest
, Construct
) {
61 SkRefCnt
* ref
= new SkRefCnt();
62 EXPECT_TRUE(ref
->unique());
64 // Adopt the reference from the caller on creation.
65 RefPtr
<SkRefCnt
> refptr1(AdoptRef(ref
));
66 EXPECT_TRUE(ref
->unique());
67 EXPECT_TRUE(refptr1
->unique());
69 EXPECT_EQ(ref
, &*refptr1
);
70 EXPECT_EQ(ref
, refptr1
.get());
72 RefPtr
<SkRefCnt
> refptr2(refptr1
);
73 EXPECT_FALSE(ref
->unique());
76 TEST(RefPtrTest
, DeclareAndAssign
) {
77 SkRefCnt
* ref
= new SkRefCnt();
78 EXPECT_TRUE(ref
->unique());
80 // Adopt the reference from the caller on creation.
81 RefPtr
<SkRefCnt
> refptr1
= AdoptRef(ref
);
82 EXPECT_TRUE(ref
->unique());
83 EXPECT_TRUE(refptr1
->unique());
85 EXPECT_EQ(ref
, &*refptr1
);
86 EXPECT_EQ(ref
, refptr1
.get());
88 RefPtr
<SkRefCnt
> refptr2
= refptr1
;
89 EXPECT_FALSE(ref
->unique());
92 TEST(RefPtrTest
, Assign
) {
93 SkRefCnt
* ref
= new SkRefCnt();
94 EXPECT_TRUE(ref
->unique());
96 // Adopt the reference from the caller on creation.
97 RefPtr
<SkRefCnt
> refptr1
;
98 refptr1
= AdoptRef(ref
);
99 EXPECT_TRUE(ref
->unique());
100 EXPECT_TRUE(refptr1
->unique());
102 EXPECT_EQ(ref
, &*refptr1
);
103 EXPECT_EQ(ref
, refptr1
.get());
105 RefPtr
<SkRefCnt
> refptr2
;
107 EXPECT_FALSE(ref
->unique());
110 class Subclass
: public SkRefCnt
{};
112 TEST(RefPtrTest
, Upcast
) {
113 RefPtr
<Subclass
> child
= AdoptRef(new Subclass());
114 EXPECT_TRUE(child
->unique());
116 RefPtr
<SkRefCnt
> parent
= child
;
120 EXPECT_FALSE(child
->unique());
121 EXPECT_FALSE(parent
->unique());