factory_with_allocator.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /*
  2. Copyright 2007 Tobias Schwinger
  3. Copyright 2019 Glen Joseph Fernandes
  4. (glenjofe@gmail.com)
  5. Distributed under the Boost Software License, Version 1.0.
  6. (http://www.boost.org/LICENSE_1_0.txt)
  7. */
  8. #include <boost/functional/factory.hpp>
  9. #include <boost/core/lightweight_test.hpp>
  10. #include <boost/smart_ptr/shared_ptr.hpp>
  11. class sum {
  12. public:
  13. sum(int a, int b)
  14. : value_(a + b) { }
  15. int get() const {
  16. return value_;
  17. }
  18. private:
  19. int value_;
  20. };
  21. template<class T>
  22. class creator {
  23. public:
  24. static int count;
  25. typedef T value_type;
  26. typedef T* pointer;
  27. template<class U>
  28. struct rebind {
  29. typedef creator<U> other;
  30. };
  31. creator() { }
  32. template<class U>
  33. creator(const creator<U>&) { }
  34. T* allocate(std::size_t size) {
  35. ++count;
  36. return static_cast<T*>(::operator new(sizeof(T) * size));
  37. }
  38. void deallocate(T* ptr, std::size_t) {
  39. --count;
  40. ::operator delete(ptr);
  41. }
  42. };
  43. template<class T>
  44. int creator<T>::count = 0;
  45. template<class T, class U>
  46. inline bool
  47. operator==(const creator<T>&, const creator<U>&)
  48. {
  49. return true;
  50. }
  51. template<class T, class U>
  52. inline bool
  53. operator!=(const creator<T>&, const creator<U>&)
  54. {
  55. return false;
  56. }
  57. int main()
  58. {
  59. int a = 1;
  60. int b = 2;
  61. {
  62. boost::shared_ptr<sum> s(boost::factory<boost::shared_ptr<sum>,
  63. creator<void>,
  64. boost::factory_alloc_for_pointee_and_deleter>()(a, b));
  65. BOOST_TEST(creator<sum>::count == 1);
  66. BOOST_TEST(s->get() == 3);
  67. }
  68. BOOST_TEST(creator<sum>::count == 0);
  69. {
  70. boost::shared_ptr<sum> s(boost::factory<boost::shared_ptr<sum>,
  71. creator<void>,
  72. boost::factory_passes_alloc_to_smart_pointer>()(a, b));
  73. BOOST_TEST(creator<sum>::count == 1);
  74. BOOST_TEST(s->get() == 3);
  75. }
  76. BOOST_TEST(creator<sum>::count == 0);
  77. return boost::report_errors();
  78. }