allocate_unique_construct_test.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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_NO_CXX11_SMART_PTR) && !defined(BOOST_NO_CXX11_ALLOCATOR)
  9. #include <boost/smart_ptr/allocate_unique.hpp>
  10. #include <boost/core/lightweight_test.hpp>
  11. struct allow { };
  12. template<class T = void>
  13. struct creator {
  14. typedef T value_type;
  15. template<class U>
  16. struct rebind {
  17. typedef creator<U> other;
  18. };
  19. creator() { }
  20. template<class U>
  21. creator(const creator<U>&) { }
  22. T* allocate(std::size_t size) {
  23. return static_cast<T*>(::operator new(sizeof(T) * size));
  24. }
  25. void deallocate(T* ptr, std::size_t) {
  26. ::operator delete(ptr);
  27. }
  28. template<class U>
  29. void construct(U* ptr) {
  30. ::new(static_cast<void*>(ptr)) U(allow());
  31. }
  32. template<class U>
  33. void destroy(U* ptr) {
  34. ptr->~U();
  35. }
  36. };
  37. template<class T, class U>
  38. inline bool
  39. operator==(const creator<T>&, const creator<U>&)
  40. {
  41. return true;
  42. }
  43. template<class T, class U>
  44. inline bool
  45. operator!=(const creator<T>&, const creator<U>&)
  46. {
  47. return false;
  48. }
  49. class type {
  50. public:
  51. static unsigned instances;
  52. explicit type(allow) {
  53. ++instances;
  54. }
  55. ~type() {
  56. --instances;
  57. }
  58. private:
  59. type(const type&);
  60. type& operator=(const type&);
  61. };
  62. unsigned type::instances = 0;
  63. int main()
  64. {
  65. {
  66. std::unique_ptr<type,
  67. boost::alloc_deleter<type, creator<type> > > result =
  68. boost::allocate_unique<type>(creator<type>());
  69. BOOST_TEST(result.get() != 0);
  70. BOOST_TEST(type::instances == 1);
  71. result.reset();
  72. BOOST_TEST(type::instances == 0);
  73. }
  74. {
  75. std::unique_ptr<const type,
  76. boost::alloc_deleter<const type, creator<> > > result =
  77. boost::allocate_unique<const type>(creator<>());
  78. BOOST_TEST(result.get() != 0);
  79. BOOST_TEST(type::instances == 1);
  80. result.reset();
  81. BOOST_TEST(type::instances == 0);
  82. }
  83. return boost::report_errors();
  84. }
  85. #else
  86. int main()
  87. {
  88. return 0;
  89. }
  90. #endif