blob: a74e05e7b2467fab0133cd0b6dc4e7c7039aa268 [file] [log] [blame]
Manuel Klimek31becd72012-01-31 19:58:34 +00001//===- 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
13namespace llvm {
14
15struct VirtualRefCounted : public RefCountedBaseVPTR {
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +000016 virtual void f();
Manuel Klimek31becd72012-01-31 19:58:34 +000017};
18
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +000019// Provide out-of-line definition to prevent weak vtable.
20void VirtualRefCounted::f() {}
21
Manuel Klimek31becd72012-01-31 19:58:34 +000022// Run this test with valgrind to detect memory leaks.
23TEST(IntrusiveRefCntPtr, RefCountedBaseVPTRCopyDoesNotLeak) {
24 VirtualRefCounted *V1 = new VirtualRefCounted;
25 IntrusiveRefCntPtr<VirtualRefCounted> R1 = V1;
26 VirtualRefCounted *V2 = new VirtualRefCounted(*V1);
27 IntrusiveRefCntPtr<VirtualRefCounted> R2 = V2;
28}
29
30struct SimpleRefCounted : public RefCountedBase<SimpleRefCounted> {};
31
32// Run this test with valgrind to detect memory leaks.
33TEST(IntrusiveRefCntPtr, RefCountedBaseCopyDoesNotLeak) {
34 SimpleRefCounted *S1 = new SimpleRefCounted;
35 IntrusiveRefCntPtr<SimpleRefCounted> R1 = S1;
36 SimpleRefCounted *S2 = new SimpleRefCounted(*S1);
37 IntrusiveRefCntPtr<SimpleRefCounted> R2 = S2;
38}
39
40struct InterceptRefCounted : public RefCountedBase<InterceptRefCounted> {
41 InterceptRefCounted(bool *Released, bool *Retained)
42 : Released(Released), Retained(Retained) {}
43 bool * const Released;
44 bool * const Retained;
45};
46template <> struct IntrusiveRefCntPtrInfo<InterceptRefCounted> {
47 static void retain(InterceptRefCounted *I) {
48 *I->Retained = true;
49 I->Retain();
50 }
51 static void release(InterceptRefCounted *I) {
52 *I->Released = true;
53 I->Release();
54 }
55};
56TEST(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