alloc_function.pass.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. //===----------------------------------------------------------------------===//
  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. // <functional>
  10. // class function<R(ArgTypes...)>
  11. // template<class A> function(allocator_arg_t, const A&, const function&);
  12. #include <functional>
  13. #include <new>
  14. #include <cstdlib>
  15. #include <cassert>
  16. #include "../test_allocator.h"
  17. int new_called = 0;
  18. void* operator new(std::size_t s) throw(std::bad_alloc)
  19. {
  20. ++new_called;
  21. return std::malloc(s);
  22. }
  23. void operator delete(void* p) throw()
  24. {
  25. --new_called;
  26. std::free(p);
  27. }
  28. class A
  29. {
  30. int data_[10];
  31. public:
  32. static int count;
  33. A()
  34. {
  35. ++count;
  36. for (int i = 0; i < 10; ++i)
  37. data_[i] = i;
  38. }
  39. A(const A&) {++count;}
  40. ~A() {--count;}
  41. int operator()(int i) const
  42. {
  43. for (int j = 0; j < 10; ++j)
  44. i += data_[j];
  45. return i;
  46. }
  47. };
  48. int A::count = 0;
  49. int g(int) {return 0;}
  50. int main()
  51. {
  52. assert(new_called == 0);
  53. {
  54. std::function<int(int)> f = A();
  55. assert(A::count == 1);
  56. assert(new_called == 1);
  57. assert(f.target<A>());
  58. assert(f.target<int(*)(int)>() == 0);
  59. std::function<int(int)> f2(std::allocator_arg, test_allocator<A>(), f);
  60. assert(A::count == 2);
  61. assert(new_called == 2);
  62. assert(f2.target<A>());
  63. assert(f2.target<int(*)(int)>() == 0);
  64. }
  65. assert(A::count == 0);
  66. assert(new_called == 0);
  67. {
  68. std::function<int(int)> f = g;
  69. assert(new_called == 0);
  70. assert(f.target<int(*)(int)>());
  71. assert(f.target<A>() == 0);
  72. std::function<int(int)> f2(std::allocator_arg, test_allocator<int(*)(int)>(), f);
  73. assert(new_called == 0);
  74. assert(f2.target<int(*)(int)>());
  75. assert(f2.target<A>() == 0);
  76. }
  77. assert(new_called == 0);
  78. {
  79. std::function<int(int)> f;
  80. assert(new_called == 0);
  81. assert(f.target<int(*)(int)>() == 0);
  82. assert(f.target<A>() == 0);
  83. std::function<int(int)> f2(std::allocator_arg, test_allocator<int>(), f);
  84. assert(new_called == 0);
  85. assert(f2.target<int(*)(int)>() == 0);
  86. assert(f2.target<A>() == 0);
  87. }
  88. }