1// Copyright (c) 2011 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.
4
5#include <string>
6
7#include "base/memory/linked_ptr.h"
8#include "base/stringprintf.h"
9#include "testing/gtest/include/gtest/gtest.h"
10
11namespace {
12
13int num = 0;
14
15std::string history;
16
17// Class which tracks allocation/deallocation
18struct A {
19  A(): mynum(num++) { history += base::StringPrintf("A%d ctor\n", mynum); }
20  virtual ~A() { history += base::StringPrintf("A%d dtor\n", mynum); }
21  virtual void Use() { history += base::StringPrintf("A%d use\n", mynum); }
22  int mynum;
23};
24
25// Subclass
26struct B: public A {
27  B() { history += base::StringPrintf("B%d ctor\n", mynum); }
28  ~B() { history += base::StringPrintf("B%d dtor\n", mynum); }
29  virtual void Use() { history += base::StringPrintf("B%d use\n", mynum); }
30};
31
32}  // namespace
33
34TEST(LinkedPtrTest, Test) {
35  {
36    linked_ptr<A> a0, a1, a2;
37    a0 = a0;
38    a1 = a2;
39    ASSERT_EQ(a0.get(), static_cast<A*>(NULL));
40    ASSERT_EQ(a1.get(), static_cast<A*>(NULL));
41    ASSERT_EQ(a2.get(), static_cast<A*>(NULL));
42    ASSERT_TRUE(a0 == NULL);
43    ASSERT_TRUE(a1 == NULL);
44    ASSERT_TRUE(a2 == NULL);
45
46    {
47      linked_ptr<A> a3(new A);
48      a0 = a3;
49      ASSERT_TRUE(a0 == a3);
50      ASSERT_TRUE(a0 != NULL);
51      ASSERT_TRUE(a0.get() == a3);
52      ASSERT_TRUE(a0 == a3.get());
53      linked_ptr<A> a4(a0);
54      a1 = a4;
55      linked_ptr<A> a5(new A);
56      ASSERT_TRUE(a5.get() != a3);
57      ASSERT_TRUE(a5 != a3.get());
58      a2 = a5;
59      linked_ptr<B> b0(new B);
60      linked_ptr<A> a6(b0);
61      ASSERT_TRUE(b0 == a6);
62      ASSERT_TRUE(a6 == b0);
63      ASSERT_TRUE(b0 != NULL);
64      a5 = b0;
65      a5 = b0;
66      a3->Use();
67      a4->Use();
68      a5->Use();
69      a6->Use();
70      b0->Use();
71      (*b0).Use();
72      b0.get()->Use();
73    }
74
75    a0->Use();
76    a1->Use();
77    a2->Use();
78
79    a1 = a2;
80    a2.reset(new A);
81    a0.reset();
82
83    linked_ptr<A> a7;
84  }
85
86  ASSERT_EQ(history,
87    "A0 ctor\n"
88    "A1 ctor\n"
89    "A2 ctor\n"
90    "B2 ctor\n"
91    "A0 use\n"
92    "A0 use\n"
93    "B2 use\n"
94    "B2 use\n"
95    "B2 use\n"
96    "B2 use\n"
97    "B2 use\n"
98    "B2 dtor\n"
99    "A2 dtor\n"
100    "A0 use\n"
101    "A0 use\n"
102    "A1 use\n"
103    "A3 ctor\n"
104    "A0 dtor\n"
105    "A3 dtor\n"
106    "A1 dtor\n"
107  );
108}
109