alloc_construct_cxx11_test.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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_ALLOCATOR)
  9. #include <boost/core/alloc_construct.hpp>
  10. #include <boost/core/lightweight_test.hpp>
  11. class type {
  12. public:
  13. explicit type(int x)
  14. : value_(x) { }
  15. int value() const {
  16. return value_;
  17. }
  18. static int count;
  19. private:
  20. type(const type&);
  21. type& operator=(const type&);
  22. int value_;
  23. };
  24. int type::count = 0;
  25. template<class T>
  26. struct creator {
  27. typedef T value_type;
  28. creator() { }
  29. template<class U>
  30. creator(const creator<U>&) { }
  31. T* allocate(std::size_t size) {
  32. return static_cast<T*>(::operator new(sizeof(T) * size));
  33. }
  34. void deallocate(T* ptr, std::size_t) {
  35. ::operator delete(ptr);
  36. }
  37. template<class V>
  38. void construct(type* ptr, const V& value) {
  39. ::new(static_cast<void*>(ptr)) type(value + 1);
  40. ++type::count;
  41. }
  42. void destroy(type* ptr) {
  43. ptr->~type();
  44. --type::count;
  45. }
  46. };
  47. int main()
  48. {
  49. creator<type> a;
  50. type* p = a.allocate(1);
  51. boost::alloc_construct(a, p, 1);
  52. BOOST_TEST_EQ(type::count, 1);
  53. BOOST_TEST_EQ(p->value(), 2);
  54. boost::alloc_destroy(a, p);
  55. BOOST_TEST_EQ(type::count, 0);
  56. return boost::report_errors();
  57. }
  58. #else
  59. int main()
  60. {
  61. return 0;
  62. }
  63. #endif