C ++类包装/成员对齐 [英] C++ Class packing / member alignment

查看:113
本文介绍了C ++类包装/成员对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道结构打包在C ++编程中很常见(至少在低内存系统上)。但是类呢?
我知道它是有效的,因为我尝试过

I know structure packing is a common thing in C++ programming (at least on low memory systems). But what about classes. I know it works because I tried it

#include <iostream>

#pragma pack(push, 1)
class Test_Packed {
    uint8_t t;
    uint32_t test;
};
#pragma pack(pop)

class Test_Unpacked {
    uint8_t t;
    uint32_t test;
};

int main() {
    std::cout<<sizeof(Test_Packed) << " / " << sizeof(Test_Unpacked)<<std::endl;
    return 0;
}

正确输出 5/8。

我可以假定所有符合条件的编译器都是这种情况吗,还是定义了此实现?

Can I assume this to be the case on all conforming Compilers, or is this implementation defined?

我知道添加虚拟成员(并且因此需要一个vtable)将在前面添加其他数据。失败的其他原因还有什么?

I know that adding virtual members (and thus needing a vtable) will add additional data in the front. What can be other reasons for this to fail?

除了某些平台上的性能不佳之外,这是否会引起其他问题?

Can this cause any problems except for poor performance on some platforms?

推荐答案

#pragma 状态:


实施定义的行为由 #pragma 指令。

所以 #pragma pack(push,1)的效果(如果有) #pragma pack(pop)
完全实现定义。

这篇关于C ++类包装/成员对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆