1 //===- unittest/ADT/IntrusiveRefCntPtrTest.cpp ----------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/ADT/IntrusiveRefCntPtr.h"
11 #include "gtest/gtest.h"
12
13 namespace llvm {
14
15 namespace {
16 struct SimpleRefCounted : public RefCountedBase<SimpleRefCounted> {
SimpleRefCountedllvm::__anon09aff92f0111::SimpleRefCounted17 SimpleRefCounted() { ++NumInstances; }
SimpleRefCountedllvm::__anon09aff92f0111::SimpleRefCounted18 SimpleRefCounted(const SimpleRefCounted &) : RefCountedBase() {
19 ++NumInstances;
20 }
~SimpleRefCountedllvm::__anon09aff92f0111::SimpleRefCounted21 ~SimpleRefCounted() { --NumInstances; }
22
23 static int NumInstances;
24 };
25 int SimpleRefCounted::NumInstances = 0;
26 } // anonymous namespace
27
TEST(IntrusiveRefCntPtr,RefCountedBaseCopyDoesNotLeak)28 TEST(IntrusiveRefCntPtr, RefCountedBaseCopyDoesNotLeak) {
29 EXPECT_EQ(0, SimpleRefCounted::NumInstances);
30 {
31 SimpleRefCounted *S1 = new SimpleRefCounted;
32 IntrusiveRefCntPtr<SimpleRefCounted> R1 = S1;
33 SimpleRefCounted *S2 = new SimpleRefCounted(*S1);
34 IntrusiveRefCntPtr<SimpleRefCounted> R2 = S2;
35 EXPECT_EQ(2, SimpleRefCounted::NumInstances);
36 }
37 EXPECT_EQ(0, SimpleRefCounted::NumInstances);
38 }
39
40 struct InterceptRefCounted : public RefCountedBase<InterceptRefCounted> {
InterceptRefCountedllvm::InterceptRefCounted41 InterceptRefCounted(bool *Released, bool *Retained)
42 : Released(Released), Retained(Retained) {}
43 bool * const Released;
44 bool * const Retained;
45 };
46 template <> struct IntrusiveRefCntPtrInfo<InterceptRefCounted> {
retainllvm::IntrusiveRefCntPtrInfo47 static void retain(InterceptRefCounted *I) {
48 *I->Retained = true;
49 I->Retain();
50 }
releasellvm::IntrusiveRefCntPtrInfo51 static void release(InterceptRefCounted *I) {
52 *I->Released = true;
53 I->Release();
54 }
55 };
TEST(IntrusiveRefCntPtr,UsesTraitsToRetainAndRelease)56 TEST(IntrusiveRefCntPtr, UsesTraitsToRetainAndRelease) {
57 bool Released = false;
58 bool Retained = false;
59 {
60 InterceptRefCounted *I = new InterceptRefCounted(&Released, &Retained);
61 IntrusiveRefCntPtr<InterceptRefCounted> R = I;
62 }
63 EXPECT_TRUE(Released);
64 EXPECT_TRUE(Retained);
65 }
66
67 } // end namespace llvm
68