auto_ptr.pass.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. //===----------------------------------------------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is dual licensed under the MIT and the University of Illinois Open
  6. // Source Licenses. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. // <memory>
  10. // template<class Y> explicit shared_ptr(auto_ptr<Y>&& r);
  11. #include <memory>
  12. #include <new>
  13. #include <cstdlib>
  14. #include <cassert>
  15. bool throw_next = false;
  16. void* operator new(std::size_t s) throw(std::bad_alloc)
  17. {
  18. if (throw_next)
  19. throw std::bad_alloc();
  20. return std::malloc(s);
  21. }
  22. void operator delete(void* p) throw()
  23. {
  24. std::free(p);
  25. }
  26. struct B
  27. {
  28. static int count;
  29. B() {++count;}
  30. B(const B&) {++count;}
  31. virtual ~B() {--count;}
  32. };
  33. int B::count = 0;
  34. struct A
  35. : public B
  36. {
  37. static int count;
  38. A() {++count;}
  39. A(const A&) {++count;}
  40. ~A() {--count;}
  41. };
  42. int A::count = 0;
  43. int main()
  44. {
  45. {
  46. std::auto_ptr<A> ptr(new A);
  47. A* raw_ptr = ptr.get();
  48. #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
  49. std::shared_ptr<B> p(std::move(ptr));
  50. #else
  51. std::shared_ptr<B> p(ptr);
  52. #endif
  53. assert(A::count == 1);
  54. assert(B::count == 1);
  55. assert(p.use_count() == 1);
  56. assert(p.get() == raw_ptr);
  57. assert(ptr.get() == 0);
  58. }
  59. assert(A::count == 0);
  60. {
  61. std::auto_ptr<A> ptr(new A);
  62. A* raw_ptr = ptr.get();
  63. throw_next = true;
  64. try
  65. {
  66. #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
  67. std::shared_ptr<B> p(std::move(ptr));
  68. #else
  69. std::shared_ptr<B> p(ptr);
  70. #endif
  71. assert(false);
  72. }
  73. catch (...)
  74. {
  75. #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
  76. assert(A::count == 1);
  77. assert(B::count == 1);
  78. assert(ptr.get() == raw_ptr);
  79. #else
  80. // Without rvalue references, ptr got copied into
  81. // the shared_ptr destructor and the copy was
  82. // destroyed during unwinding.
  83. assert(A::count == 0);
  84. assert(B::count == 0);
  85. #endif
  86. }
  87. }
  88. assert(A::count == 0);
  89. }