allocate_local_shared_array_esft_test.cpp 2.1 KB

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