If I define a simple type with a certain alignment requirement, shouldn\'t a std::vector
of said type honour the alignment for every single element
first, that std::allocator ignores any alignment requirements even for the first element (illegal?)
I'm far from being an expert on allocators but it seems to me that, unfortunately, this is legal behaviour. More precisely, an allocator might ignore the requested alignment. Indeed, [allocator.requirements], 17.6.3.5/6 states:
If the alignment associated with a specific over-aligned type is not supported by an allocator, instantiation of the allocator for that type may fail. The allocator also may silently ignore the requested alignment.
You can write your own allocator to give you aligned memory. I've done that before at my work but, unfortunately, for copyright reasons, I cannot disclose the code :-( All I can say, is the obvious thing: it was based on _aligned_malloc
and _aligned_free
(which are Microsoft extensions). Or you can Google for "aligned allocator" and a few options will come up, one of which is
https://gist.github.com/donny-dont/1471329
I emphasize that I'm not the author of this aligned allocator and I've never used it.
Update
The aligned allocator above is for Visual Studio/Windows but it can be used as a base for implementing aligned allocators on other platforms. You can use the posix memalign family of functions or the C11 function aligned_alloc
.
See this post.