IntrusiveRefCntPtrTest.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. #include "llvm/ADT/IntrusiveRefCntPtr.h"
  10. #include "gtest/gtest.h"
  11. namespace {
  12. struct VirtualRefCounted : public llvm::RefCountedBaseVPTR {
  13. virtual void f() {}
  14. };
  15. }
  16. namespace llvm {
  17. // Run this test with valgrind to detect memory leaks.
  18. TEST(IntrusiveRefCntPtr, RefCountedBaseVPTRCopyDoesNotLeak) {
  19. VirtualRefCounted *V1 = new VirtualRefCounted;
  20. IntrusiveRefCntPtr<VirtualRefCounted> R1 = V1;
  21. VirtualRefCounted *V2 = new VirtualRefCounted(*V1);
  22. IntrusiveRefCntPtr<VirtualRefCounted> R2 = V2;
  23. }
  24. struct SimpleRefCounted : public RefCountedBase<SimpleRefCounted> {};
  25. // Run this test with valgrind to detect memory leaks.
  26. TEST(IntrusiveRefCntPtr, RefCountedBaseCopyDoesNotLeak) {
  27. SimpleRefCounted *S1 = new SimpleRefCounted;
  28. IntrusiveRefCntPtr<SimpleRefCounted> R1 = S1;
  29. SimpleRefCounted *S2 = new SimpleRefCounted(*S1);
  30. IntrusiveRefCntPtr<SimpleRefCounted> R2 = S2;
  31. }
  32. struct InterceptRefCounted : public RefCountedBase<InterceptRefCounted> {
  33. InterceptRefCounted(bool *Released, bool *Retained)
  34. : Released(Released), Retained(Retained) {}
  35. bool * const Released;
  36. bool * const Retained;
  37. };
  38. template <> struct IntrusiveRefCntPtrInfo<InterceptRefCounted> {
  39. static void retain(InterceptRefCounted *I) {
  40. *I->Retained = true;
  41. I->Retain();
  42. }
  43. static void release(InterceptRefCounted *I) {
  44. *I->Released = true;
  45. I->Release();
  46. }
  47. };
  48. TEST(IntrusiveRefCntPtr, UsesTraitsToRetainAndRelease) {
  49. bool Released = false;
  50. bool Retained = false;
  51. {
  52. InterceptRefCounted *I = new InterceptRefCounted(&Released, &Retained);
  53. IntrusiveRefCntPtr<InterceptRefCounted> R = I;
  54. }
  55. EXPECT_TRUE(Released);
  56. EXPECT_TRUE(Retained);
  57. }
  58. } // end namespace llvm