linked_ptr_unittest.cc 2.3 KB

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