allocate_unique_args_test.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. /*
  2. Copyright 2019 Glen Joseph Fernandes
  3. (glenjofe@gmail.com)
  4. Distributed under the Boost Software License, Version 1.0.
  5. (http://www.boost.org/LICENSE_1_0.txt)
  6. */
  7. #include <boost/config.hpp>
  8. #if (!defined(BOOST_LIBSTDCXX_VERSION) || \
  9. BOOST_LIBSTDCXX_VERSION >= 46000) && \
  10. !defined(BOOST_NO_CXX11_SMART_PTR) && \
  11. !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
  12. #include <boost/smart_ptr/allocate_unique.hpp>
  13. #include <boost/core/lightweight_test.hpp>
  14. template<class T = void>
  15. struct creator {
  16. typedef T value_type;
  17. typedef T* pointer;
  18. template<class U>
  19. struct rebind {
  20. typedef creator<U> other;
  21. };
  22. creator() { }
  23. template<class U>
  24. creator(const creator<U>&) { }
  25. T* allocate(std::size_t size) {
  26. return static_cast<T*>(::operator new(sizeof(T) * size));
  27. }
  28. void deallocate(T* ptr, std::size_t) {
  29. ::operator delete(ptr);
  30. }
  31. };
  32. template<class T, class U>
  33. inline bool
  34. operator==(const creator<T>&, const creator<U>&)
  35. {
  36. return true;
  37. }
  38. template<class T, class U>
  39. inline bool
  40. operator!=(const creator<T>&, const creator<U>&)
  41. {
  42. return false;
  43. }
  44. class type {
  45. public:
  46. static unsigned instances;
  47. type(int v1, int v2, int v3, int v4, int v5)
  48. : sum_(v1 + v2 + v3 + v4 + v5) {
  49. ++instances;
  50. }
  51. ~type() {
  52. --instances;
  53. }
  54. int sum() const {
  55. return sum_;
  56. }
  57. private:
  58. int sum_;
  59. type(const type&);
  60. type& operator=(const type&);
  61. };
  62. unsigned type::instances = 0;
  63. int main()
  64. {
  65. BOOST_TEST(type::instances == 0);
  66. {
  67. std::unique_ptr<type,
  68. boost::alloc_deleter<type, creator<type> > > result =
  69. boost::allocate_unique<type>(creator<type>(), 1, 2, 3, 4, 5);
  70. BOOST_TEST(result.get() != 0);
  71. BOOST_TEST(type::instances == 1);
  72. BOOST_TEST(result->sum() == 15);
  73. result.reset();
  74. BOOST_TEST(type::instances == 0);
  75. }
  76. BOOST_TEST(type::instances == 0);
  77. {
  78. std::unique_ptr<const type,
  79. boost::alloc_deleter<const type, creator<> > > result =
  80. boost::allocate_unique<const type>(creator<>(), 1, 2, 3, 4, 5);
  81. BOOST_TEST(result.get() != 0);
  82. BOOST_TEST(type::instances == 1);
  83. BOOST_TEST(result->sum() == 15);
  84. result.reset();
  85. BOOST_TEST(type::instances == 0);
  86. }
  87. return boost::report_errors();
  88. }
  89. #else
  90. int main()
  91. {
  92. return 0;
  93. }
  94. #endif