UniqueObjectAllocator.hpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #ifndef BOOST_STATECHART_EXAMPLE_UNIQUE_OBJECT_ALLOCATOR_HPP_INCLUDED
  2. #define BOOST_STATECHART_EXAMPLE_UNIQUE_OBJECT_ALLOCATOR_HPP_INCLUDED
  3. //////////////////////////////////////////////////////////////////////////////
  4. // Copyright 2002-2006 Andreas Huber Doenni
  5. // Distributed under the Boost Software License, Version 1.0. (See accompany-
  6. // ing file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  7. //////////////////////////////////////////////////////////////////////////////
  8. #include <boost/statechart/detail/avoid_unused_warning.hpp>
  9. #include <boost/config.hpp>
  10. #ifdef BOOST_MSVC
  11. # pragma warning( push )
  12. # pragma warning( disable: 4511 ) // copy constructor could not be generated
  13. # pragma warning( disable: 4512 ) // assignment operator could not be generated
  14. #endif
  15. #include <boost/type_traits/alignment_of.hpp>
  16. #ifdef BOOST_MSVC
  17. # pragma warning( pop )
  18. #endif
  19. #include <boost/type_traits/type_with_alignment.hpp>
  20. #include <boost/assert.hpp>
  21. #include <cstddef> // size_t
  22. //////////////////////////////////////////////////////////////////////////////
  23. template< class T >
  24. class UniqueObjectAllocator
  25. {
  26. public:
  27. //////////////////////////////////////////////////////////////////////////
  28. static void * allocate( std::size_t size )
  29. {
  30. boost::statechart::detail::avoid_unused_warning( size );
  31. BOOST_ASSERT( !constructed_ && ( size == sizeof( T ) ) );
  32. constructed_ = true;
  33. return &storage_.data_[ 0 ];
  34. }
  35. static void deallocate( void * p, std::size_t size )
  36. {
  37. boost::statechart::detail::avoid_unused_warning( p );
  38. boost::statechart::detail::avoid_unused_warning( size );
  39. BOOST_ASSERT( constructed_ &&
  40. ( p == &storage_.data_[ 0 ] ) && ( size == sizeof( T ) ) );
  41. constructed_ = false;
  42. }
  43. private:
  44. //////////////////////////////////////////////////////////////////////////
  45. union storage
  46. {
  47. char data_[ sizeof( T ) ];
  48. typename boost::type_with_alignment<
  49. boost::alignment_of< T >::value >::type aligner_;
  50. };
  51. static bool constructed_;
  52. static storage storage_;
  53. };
  54. template< class T >
  55. bool UniqueObjectAllocator< T >::constructed_ = false;
  56. template< class T >
  57. typename UniqueObjectAllocator< T >::storage
  58. UniqueObjectAllocator< T >::storage_;
  59. #endif