allocate_shared_array_esft_test.cpp 2.0 KB

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