optional_aligned_storage.hpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright (C) 2003, 2008 Fernando Luis Cacciola Carballal.
  2. // Copyright (C) 2016 Andrzej Krzemienski.
  3. //
  4. // Use, modification, and distribution is subject to the Boost Software
  5. // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
  6. // http://www.boost.org/LICENSE_1_0.txt)
  7. //
  8. // See http://www.boost.org/libs/optional for documentation.
  9. //
  10. // You are welcome to contact the author at:
  11. // fernando_cacciola@hotmail.com
  12. // akrzemi1@gmail.com
  13. #ifndef BOOST_OPTIONAL_OPTIONAL_DETAIL_OPTIONAL_ALIGNED_STORAGE_AJK_12FEB2016_HPP
  14. #define BOOST_OPTIONAL_OPTIONAL_DETAIL_OPTIONAL_ALIGNED_STORAGE_AJK_12FEB2016_HPP
  15. namespace boost {
  16. namespace optional_detail {
  17. // This local class is used instead of that in "aligned_storage.hpp"
  18. // because I've found the 'official' class to ICE BCB5.5
  19. // when some types are used with optional<>
  20. // (due to sizeof() passed down as a non-type template parameter)
  21. template <class T>
  22. class aligned_storage
  23. {
  24. // Borland ICEs if unnamed unions are used for this!
  25. // BOOST_MAY_ALIAS works around GCC warnings about breaking strict aliasing rules when casting storage address to T*
  26. union BOOST_MAY_ALIAS dummy_u
  27. {
  28. char data[ sizeof(T) ];
  29. BOOST_DEDUCED_TYPENAME type_with_alignment<
  30. ::boost::alignment_of<T>::value >::type aligner_;
  31. } dummy_ ;
  32. public:
  33. #if defined(BOOST_OPTIONAL_DETAIL_USE_ATTRIBUTE_MAY_ALIAS)
  34. void const* address() const { return &dummy_; }
  35. void * address() { return &dummy_; }
  36. #else
  37. void const* address() const { return dummy_.data; }
  38. void * address() { return dummy_.data; }
  39. #endif
  40. #if defined(BOOST_OPTIONAL_DETAIL_USE_ATTRIBUTE_MAY_ALIAS)
  41. // This workaround is supposed to silence GCC warnings about broken strict aliasing rules
  42. T const* ptr_ref() const
  43. {
  44. union { void const* ap_pvoid; T const* as_ptype; } caster = { address() };
  45. return caster.as_ptype;
  46. }
  47. T * ptr_ref()
  48. {
  49. union { void* ap_pvoid; T* as_ptype; } caster = { address() };
  50. return caster.as_ptype;
  51. }
  52. #else
  53. T const* ptr_ref() const { return static_cast<T const*>(address()); }
  54. T * ptr_ref() { return static_cast<T *> (address()); }
  55. #endif
  56. T const& ref() const { return *ptr_ref(); }
  57. T & ref() { return *ptr_ref(); }
  58. } ;
  59. } // namespace optional_detail
  60. } // namespace boost
  61. #endif // header guard