类连续数据 [英] Class contiguous data

查看:100
本文介绍了类连续数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C ++类,它有四个私有浮点和一堆非静态公共函数,对这些数据进行操作。

I have a C++ class which has four private floats and a bunch of nonstatic public functions that operate on this data.

是保证还是可能所以,四个浮点是连续的,没有填充。这将使类的大小为四个浮点,它的地址将是第一个浮点的。

Is it guaranteed, or possible to make it so, that the four floats are contiguous and there is no padding. This would make the class the size of four floats, and it's address would be that of the first float.

推荐答案

您的编译器。

您可以使用 #pragma pack(1) MSVC gcc #pragma pack 1 aCC

例如,假设 MSVC / gcc

#pragma pack(1)
class FourFloats
{
    float f1, f2, f3, f4;
};

或更好:

#pragma pack(push, 1)
class FourFloats
{
    float f1, f2, f3, f4;
};
#pragma pack(pop)

基本上禁用填充并保证 floats 是连续的。但是,为了确保类的大小实际上是 4 * sizeof(float),它不能有 vtbl ,表示虚拟成员是禁用的。

That basically disables padding and guarantees that the floats are contiguous. However, to ensure that the size of your class is actually 4 * sizeof(float), it must not have a vtbl, which means virtual members are off-limits.

这篇关于类连续数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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