I'm trying to allocate a block of memory of size size
which needs to be Alignment
aligned where the size may not be defined at compile time. I know routines such as _aligned_alloc
, posix_memalign
, _mm_alloc
, etc exist but I do not want to use them as they bring down code portability.
C++11 gives a routine std::align
and also a class std::aligned_storage
from which I can retrieve a POD type to allocate an element which will be aligned to my requirements. However my goal is to create an allocator which would allocate a block of memory of size
size (not just a single element) which would be aligned.
Is this possible using std::align
? The reason I ask is since std::align
moves the pointer, the class using that pointer will give the allocator a pointer to the moved address for deallocation which would be invalid. Is there a way to create an aligned_allocator this way?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
If it HAS TO BE a C++11 solution, then ignore this answer.
If not... I don't know if you already know this, but here is one option:
Perhaps
malloc
andfree
are not 100% portable, but it's easy to handle such cases with preprocessor directives.EDIT: after clarifications from the OP, it appears the original answer is off-topic; for reference's sake it is kept at the end of this answer.
Actually, the answer is rather simple: you simply need to keep a pointer both to the storage block and to the first item.
This does not, actually, requires a stateful allocator (it could be possible even in C++03, albeit with a custom
std::align
routine). The trick is that the allocator is not required to only ask of the system exactly enough memory to store user data. It can perfectly ask a bit more for book-keeping purposes of its own.So, here we go creating an aligned allocator; to keep it simple I'll focus on the allocation/deallocation routines.
And now the allocation routine. Lots of memory fiddling, it's the heart of the allocator after all!
Fortunately the deallocation routine is much simpler, it just has to read the offset and apply it.
The other routines need not be aware of the memory layout, so writing them is trivial.
Original answer: