I'm a bit confused about the alignement requirements when std::aligned_storage
is used and dynamic allocation is needed. Example:
using storage = typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type;
storage* pool;
pool = ::new storage[num_obj];
Is it legal? The new operator doesn't return alignment memory, so is the result correct?
Alignment refers to the arrangement of data in memory, and specifically deals with the issue of accessing data as proper units of information from main memory. First we must conceptualize main memory as a contiguous block of consecutive memory locations. Each location contains a fixed number of bits.
For the purpose of dynamic storage allocation, we view memory as a single array broken into a series of variable-size blocks, where some of the blocks are free blocks and some are reserved blocks or already allocated. The free blocks are linked together to form a freelist used for servicing future memory requests.
Dynamic allocation can be handled in one of two general ways: • Stack allocation (hierarchical): restricted, but simple and efficient. Heap allocation: more general, but less efficient, more difficult to implement.
A way or organizing different types of data in the phone's memory. Also referred to as Shared memory. Dynamic memory means that all types of data are stored in the same memory (there is no separate memory for photos, ringtones etc.).
The C++11 standard requires that allocation functions such as ::operator new
return memory that is aligned to alignof(std::max_align_t)
[basic.stc.dynamic/2]:
The pointer returned shall be suitably aligned so that it can be converted to a pointer of any complete object type with a fundamental alignment requirement […]
Thus, as long as the type of the object you're creating via your new
expression is not an overaligned type (one that requires an alignment more strict than alignof(std::max_align_t)
), everything's fine. For overaligned types, you would indeed have to allocate storage of sufficient size to manually align the pointer, e.g., using std::align
, and then construct your object at a suitable address, e.g., via placement new…
Starting with C++17, new
automatically takes care of this. To allocate storage that requires alignment more strict than __STDCPP_DEFAULT_NEW_ALIGNMENT__
(the alignment that allocation functions are at least required to supply), a new-expression will call an allocation function that is explicitly given the alignment of the storage to be allocated as an argument [expr.new]/14 …
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With