1 /* 2 * Copyright 2011 Google Inc. All Rights Reserved. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #include "gtest/gtest.h" 18 #define ENABLE_OBJECT_COUNTER 19 #include "sfntly/port/refcount.h" 20 21 using sfntly::RefCounted; 22 using sfntly::Ptr; 23 24 class Foo : public RefCounted<Foo> { 25 public: // put in something to make sure it's not empty 26 int foo_; 27 int foo() { return foo_; } 28 }; 29 30 bool TestSmartPointer() { 31 // scope out allocation 32 { 33 Ptr<Foo> p1; 34 p1 = new Foo(); 35 EXPECT_EQ(size_t(1), p1->ref_count_); 36 EXPECT_EQ(size_t(1), RefCounted<Foo>::object_counter_); 37 38 Ptr<Foo> p2; 39 p2 = p1; 40 EXPECT_EQ(size_t(2), p1->ref_count_); 41 EXPECT_EQ(size_t(2), p2->ref_count_); 42 EXPECT_EQ(size_t(1), RefCounted<Foo>::object_counter_); 43 44 Ptr<Foo> p3; 45 p3 = p1; 46 EXPECT_EQ(size_t(3), p1->ref_count_); 47 EXPECT_EQ(size_t(3), p2->ref_count_); 48 EXPECT_EQ(size_t(3), p3->ref_count_); 49 EXPECT_EQ(size_t(1), RefCounted<Foo>::object_counter_); 50 51 p2 = new Foo(); 52 EXPECT_EQ(size_t(2), p1->ref_count_); 53 EXPECT_EQ(size_t(1), p2->ref_count_); 54 EXPECT_EQ(size_t(2), p3->ref_count_); 55 EXPECT_EQ(size_t(2), RefCounted<Foo>::object_counter_); 56 57 p3.Release(); 58 EXPECT_EQ(size_t(1), p1->ref_count_); 59 EXPECT_EQ(NULL, p3.p_); 60 EXPECT_EQ(size_t(2), RefCounted<Foo>::object_counter_); 61 62 p2 = NULL; 63 EXPECT_EQ(size_t(1), RefCounted<Foo>::object_counter_); 64 65 p1 = p1; 66 EXPECT_EQ(size_t(1), p1->ref_count_); 67 EXPECT_EQ(size_t(1), RefCounted<Foo>::object_counter_); 68 69 p1 = &(*p1); 70 EXPECT_EQ(size_t(1), p1->ref_count_); 71 EXPECT_EQ(size_t(1), RefCounted<Foo>::object_counter_); 72 } 73 EXPECT_EQ(size_t(0), RefCounted<Foo>::object_counter_); 74 return true; 75 } 76 77 TEST(SmartPointer, All) { 78 ASSERT_TRUE(TestSmartPointer()); 79 } 80