如何保证成员4字节对齐?
为了使用 OSAtomicDecrement(mac 特定的原子操作),我需要提供一个 4 字节对齐的 SInt32。
这样的煮法有用吗?还有其他方法可以解决对齐问题吗?
struct SomeClass {
SomeClass() {
member_ = &storage_ + ((4 - (&storage_ % 4)) % 4);
*member_ = 0;
}
SInt32 *member_;
struct {
SInt32 a;
SInt32 b;
} storage_;
};
In order to use OSAtomicDecrement (mac-specific atomic operation), I need to provide a 4-byte aligned SInt32.
Does this kind of cooking work ? Is there another way to deal with alignment issues ?
struct SomeClass {
SomeClass() {
member_ = &storage_ + ((4 - (&storage_ % 4)) % 4);
*member_ = 0;
}
SInt32 *member_;
struct {
SInt32 a;
SInt32 b;
} storage_;
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果您使用的是 Mac,则意味着 GCC。 GCC 可以为您自动对齐变量:
请注意,这不能跨编译器移植,因为这是 GCC 特定的。
If you're on a Mac, that means GCC. GCC can auto align variables for you:
Please note that this is not portable across compilers, as this is GCC specific.
我猜想任何 SInt32 都已经对齐,即使在 Mac 上也是如此。
澄清一下:
member 始终正确对齐,除非您打包结构并将 member 放在字符后面。
I would guess that any SInt32 is already aligned, even on a mac.
To clarify:
member is always aligned properly, unless you pack the structure and put member after a char.
默认情况下,
int
与任何 OS X 编译器都是 4 字节对齐的。您需要做的就是不要故意破坏该对齐方式(例如,通过执行不正确的指针转换、将您的结构标记为“打包”等)。int
s are 4 byte aligned by default with any of the OS X compilers. All you need to do is not intentionally break that alignment (e.g. by doing improper pointer casts, marking your structure aspacked
, etc).我对 Mac 编程一无所知,但在我曾经使用过的小型计算机上,指针总是在 4 字节(字)边界上对齐。 IIRC,结构也是如此。分配的内存总是如此。
I know nothing about Mac programming but on minicomputers that I used to work on, pointers were always aligned on 4-byte (word) boundaries. IIRC, structs were too. Allocated memory always was.
如果您的编译器支持 TR1(或 C++0x),则可以使用
std::aligned_storage
模板。要为大小为
S
且对齐方式为A
的对象分配空间,您可以分配std::aligned_storage
::storage< 类型的对象/代码>。(命名空间可能因编译器而异。我认为 TR1 没有指定扩展必须放置在哪个命名空间中。在 MSVC 上,使用命名空间
std::tr1
)除此之外,32 位编译器已经将整数进行 4 字节对齐(至少在 32 位整数的自然对齐为 4 字节的平台上)
If your compiler supports TR1 (or C++0x), you can use the
std::aligned_storage
template.To allocate space for an object with size
S
and alignmentA
, you can allocate an object of typestd::aligned_storage<S, A>::storage
.(The namespace may vary between compilers. I think TR1 doesn't specify which namespace the extensions must be placed in. On MSVC, the namespace
std::tr1
is used)Apart from this, 32-bit integers are already 4-byte aligned by the compiler (at least on the platforms where the natural alignment of 32-bit ints is 4 bytes)
如果您想在结构中强制进行良好的对齐,可以使用位字段。
If you want to force a nice alignment in a structure, you can use bit fields.