Brian Silverman | 4a2409e | 2018-08-04 23:24:02 -0700 | [diff] [blame^] | 1 | [/ |
| 2 | Copyright 2007 John Maddock. |
| 3 | Distributed under the Boost Software License, Version 1.0. |
| 4 | (See accompanying file LICENSE_1_0.txt or copy at |
| 5 | http://www.boost.org/LICENSE_1_0.txt). |
| 6 | ] |
| 7 | |
| 8 | [section:aligned_storage aligned_storage] |
| 9 | |
| 10 | template <std::size_t Size, std::size_t Align> |
| 11 | struct aligned_storage |
| 12 | { |
| 13 | typedef __below type; |
| 14 | }; |
| 15 | |
| 16 | __type a built-in or POD type with size `Size` and an alignment |
| 17 | that is a multiple of `Align`. |
| 18 | |
| 19 | __header ` #include <boost/type_traits/aligned_storage.hpp>` or ` #include <boost/type_traits.hpp>` |
| 20 | |
| 21 | On the GCC and Visual C++ compilers (or compilers that are compatible with them), we support |
| 22 | requests for types with alignments greater than any built in type (up to 128-bit alignment). |
| 23 | Visual C++ users should note that such "extended" types can not be passed down the stack as |
| 24 | by-value function arguments. |
| 25 | |
| 26 | [important |
| 27 | Visual C++ users should be aware that MSVC has an elastic definition of alignment, for |
| 28 | example consider the following code: |
| 29 | |
| 30 | `` |
| 31 | typedef boost::aligned_storage<8,8>::type align_t; |
| 32 | assert(boost::alignment_of<align_t>::value % 8 == 0); |
| 33 | align_t a; |
| 34 | assert(((std::uintptr_t)&a % 8) == 0); |
| 35 | char c = 0; |
| 36 | align_t a1; |
| 37 | assert(((std::uintptr_t)&a1 % 8) == 0); |
| 38 | `` |
| 39 | |
| 40 | In this code the final assert will fail for a 32-bit build because variable `a1` is not |
| 41 | aligned on an 8-byte boundary. Had we used the MSVC intrinsic `__alignof` in |
| 42 | place of `alignment_of` or `std::aligned_storage` in place of `boost::aligned_storage` |
| 43 | the result would have been no different. In MSVC alignment requirements/promises only |
| 44 | really apply to variables on the heap, not on the stack. |
| 45 | |
| 46 | Further, although MSVC has a mechanism for generating new types with arbitrary alignment |
| 47 | requirements, such types cannot be passed as function arguments on the program stack. |
| 48 | Therefore had `boost::aligned_storage<8,8>::type` been a type declared with |
| 49 | `__declspec(align(8))` we would break a great deal of existing code that relies on |
| 50 | being able to pass such types through the program stack. |
| 51 | ] |
| 52 | |
| 53 | [endsect] |
| 54 | |