为什么需要这段代码?
typedef struct corr_id_{
unsigned int size:8;
unsigned int valueType:8;
unsigned int classId:8;
unsigned int reserved:8;
} CorrId;
我围绕它做了一些调查,发现通过这种方式我们将内存消耗限制在我们需要的范围内。 例如
typedef struct corr_id_new{
unsigned int size;
unsigned int valueType;
unsigned int classId;
unsigned int reserved;
} CorrId_NEW;
typedef struct corr_id_{
unsigned int size:8;
unsigned int valueType:8;
unsigned int classId:8;
unsigned int reserved:8;
} CorrId;
int main(){
CorrId_NEW Obj1;
CorrId Obj2;
std::cout<<sizeof(Obj1)<<endl;
std::cout<<sizeof(Obj2)<<endl;
}
输出:-
16
4
我想了解此类场景的真实用例?为什么我们不能像这样声明结构,
typedef struct corr_id_new{
unsigned _int8 size;
unsigned _int8 valueType;
unsigned _int8 classId;
unsigned _int8 reserved;
} CorrId_NEW;
这与编译器优化有关吗?或者,以这种方式声明结构有什么好处?
最佳答案
I want to understand the real use case of such scenarios?
例如,某些CPU的状态寄存器结构可能是这样的:
为了通过结构来表示它,您可以使用位域:
struct CSR
{
unsigned N: 1;
unsigned Z: 1;
unsigned C: 1;
unsigned V: 1;
unsigned : 20;
unsigned I: 1;
unsigned : 2;
unsigned M: 5;
};
你可以在这里看到字段不是 8 的倍数,所以你不能使用 int8_t
或类似的东西。
关于c++ - 使用 : 限制结构大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18932364/