如果你不介意浪费一点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
如果没有将整个班级对准到相同的值,则不能“排列成员”。否则,您可以通过班级允许的对齐来取代整个对象并打破成员对齐。 (这个类的布局当然是固定的,并不是每个对象都决定的。) –