In some use case, you’ll need to allocate storage before creating objects inside this storage.
Then in order to create these objects, you may need to use placement new:
T *pobj = new(pstorage);
yet you have to provide a properly aligned pstorage
.
I don’t understand the expected behavior of operator new:
// properly aligned heap storage to hold N contiguous T objects
unsigned char *storage = new unsigned char[N*sizeof(T)];
Non-overaligned types
Is the new
expression guaranteed to return a pointer to an address suitably aligned for any “non-overaligned” type (In which case, successive calls of new
for weak aligned types will lead to some kind of memory fragmentation?)?
Btw, is “T
is overaligned” equivalent to alignof(T)>alignof(std::max_align_t)
? And is it possible to have an overaligned type without using alignas
keyword?
Overaligned types
If T
is overaligned, how can I produce the right alignment?
The simplest solution I found so far was:
// in the spirit of std::aligned_storage
// can be on the stack or on the heap
template <typename T, std::size_t N>
struct Storage {
alignas(T) unsigned char storage[N * sizeof(T)];
}
auto *wrapped_storage = new Storage<T,N>;
auto *storage = wrapped_storage.storage;
1