allocate_unique_value_test.cpp 2.3 KB

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