c++ - 使用 : 限制结构大小

标签 c++

为什么需要这段代码?

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的状态寄存器结构可能是这样的:

enter image description here

为了通过结构来表示它,您可以使用位域:

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/

相关文章:

c# - 如何到达这一阶段 :

c# - 如何在c#程序中包含cpp头文件

c++ - 可以安全地修改成对 vector 中的 std::pair<U, V>::first 吗?

C++修改对象指针指向但不保留值

c++ - 我应该缓存它吗?

c++ - istringstream 没有输出正确的数据

c++ - 未实例化模板函数的处理

c++ - 如何在 Eigen C++ 中对称化稀疏矩阵?

c++ - 尝试通过 .h 和 .cpp 文件设置类——为什么会出现这些错误?

不应使用 c++ 有向字母 (MISRA C++ 2-5-1)