clone_allocator.hpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. //
  2. // Boost.Pointer Container
  3. //
  4. // Copyright Thorsten Ottosen 2003-2005. Use, modification and
  5. // distribution is subject to the Boost Software License, Version
  6. // 1.0. (See accompanying file LICENSE_1_0.txt or copy at
  7. // http://www.boost.org/LICENSE_1_0.txt)
  8. //
  9. // For more information, see http://www.boost.org/libs/ptr_container/
  10. //
  11. #ifndef BOOST_PTR_CONTAINER_CLONE_ALLOCATOR_HPP
  12. #define BOOST_PTR_CONTAINER_CLONE_ALLOCATOR_HPP
  13. #include <boost/assert.hpp>
  14. #include <boost/checked_delete.hpp>
  15. #include <typeinfo>
  16. namespace boost
  17. {
  18. /////////////////////////////////////////////////////////////////////////
  19. // Clonable concept
  20. /////////////////////////////////////////////////////////////////////////
  21. template< class T >
  22. inline T* new_clone( const T& r )
  23. {
  24. //
  25. // @remark: if you get a compile-error here,
  26. // it is most likely because you did not
  27. // define new_clone( const T& ) in the namespace
  28. // of T.
  29. //
  30. T* res = new T( r );
  31. BOOST_ASSERT( typeid(r) == typeid(*res) &&
  32. "Default new_clone() sliced object!" );
  33. return res;
  34. }
  35. template< class T >
  36. inline void delete_clone( const T* r )
  37. {
  38. checked_delete( r );
  39. }
  40. /////////////////////////////////////////////////////////////////////////
  41. // CloneAllocator concept
  42. /////////////////////////////////////////////////////////////////////////
  43. struct heap_clone_allocator
  44. {
  45. template< class U >
  46. static U* allocate_clone( const U& r )
  47. {
  48. return new_clone( r );
  49. }
  50. template< class U >
  51. static void deallocate_clone( const U* r )
  52. {
  53. delete_clone( r );
  54. }
  55. };
  56. struct view_clone_allocator
  57. {
  58. template< class U >
  59. static U* allocate_clone( const U& r )
  60. {
  61. return const_cast<U*>(&r);
  62. }
  63. template< class U >
  64. static void deallocate_clone( const U* /*r*/ )
  65. {
  66. // do nothing
  67. }
  68. };
  69. } // namespace 'boost'
  70. #endif