如果你不介意浪費一點RAM,你可以做一個aligned_holder包裝類,它將保證它所包含的對象將與你指定的任何對齊邊界對齊。 (請注意,浪費的RAM的量是等於指定對準邊界)
#include <stdio.h>
#include <stddef.h>
#include <stdint.h>
#include <new>
// Makes sure that its held object is always aligned to the specified alignment-value,
// at the cost of using up some extra RAM.
template<class T, int AlignTo=16> class aligned_holder
{
public:
aligned_holder()
{
new (getAlignedPointer()) T();
}
~aligned_holder()
{
getAlignedObject().~T();
}
T & getAlignedObject() {return *reinterpret_cast<T*>(getAlignedPointer());}
const T & getAlignedObjectConst() const {return *reinterpret_cast<const T*>(getAlignedPointerConst());}
private:
char * getAlignedPointer()
{
const ptrdiff_t offset = intptr_t(_buf)%AlignTo;
return &_buf[(intptr_t)(AlignTo-offset)];
}
const char * getAlignedPointerConst() const
{
const ptrdiff_t offset = intptr_t(_buf)%AlignTo;
return &_buf[(intptr_t)(AlignTo-offset)];
}
char _buf[AlignTo+sizeof(T)];
};
...和單元測試,以(希望)驗證我沒有弄亂例如:
class IWannaBeAligned
{
public:
IWannaBeAligned()
{
const intptr_t iThis = (intptr_t)(this);
if ((iThis % 16) != 0) printf("Error! object %p is not 16-byte aligned! (offset=%ld)\n", this, iThis%16);
else printf("Good, object %p is 16-byte aligned.\n", this);
}
~IWannaBeAligned()
{
printf("Deleting object %p\n", this);
}
char buf[32]; // just to give it a more realistic object size than one byte
};
int main()
{
{
printf("First, let's try it without the aligned_holder:\n");
IWannaBeAligned notAligned;
}
printf("\n");
{
printf("Now, we'll try it with the aligned_holder:\n");
aligned_holder<IWannaBeAligned> isAligned;
}
return 0;
}
保證類成員的本地或靜態變量以及本地或靜態數組滿足對齊要求。如果您動態分配內存,則可能會遇到問題。我猜你正在嘗試使用'std :: vector'或類似的東西?如果是這樣,那麼說。 –
你是對的,我正在嘗試使用像這樣的類的向量。任何建議? – MNagy
如果沒有將整個班級對準到相同的值,則不能「排列成員」。否則,您可以通過班級允許的對齊來取代整個對象並打破成員對齊。 (這個類的佈局當然是固定的,並不是每個對象都決定的。) –