clone_allocator.hpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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 T* new_clone( const T* r )
  37. {
  38. return r ? new_clone( *r ) : 0;
  39. }
  40. //
  41. // @remark: to make new_clone() work
  42. // with scope_ptr/shared_ptr ect.
  43. // simply overload for those types
  44. // in the appropriate namespace.
  45. //
  46. template< class T >
  47. inline void delete_clone( const T* r )
  48. {
  49. checked_delete( r );
  50. }
  51. /////////////////////////////////////////////////////////////////////////
  52. // CloneAllocator concept
  53. /////////////////////////////////////////////////////////////////////////
  54. struct heap_clone_allocator
  55. {
  56. template< class U >
  57. static U* allocate_clone( const U& r )
  58. {
  59. return new_clone( r );
  60. }
  61. template< class U >
  62. static void deallocate_clone( const U* r )
  63. {
  64. delete_clone( r );
  65. }
  66. };
  67. struct view_clone_allocator
  68. {
  69. template< class U >
  70. static U* allocate_clone( const U& r )
  71. {
  72. return const_cast<U*>(&r);
  73. }
  74. template< class U >
  75. static void deallocate_clone( const U* /*r*/ )
  76. {
  77. // do nothing
  78. }
  79. };
  80. } // namespace 'boost'
  81. #endif