为什么需要这段代码?使用限制结构尺寸:
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;
这是否与编译器优化有关?或者,以这种方式声明结构有什么好处?
实际上你应该结合这两种方法......或者使用'pack' /'packed' –
你确定输出是'4 16'而不是'16 4'吗? –
谢谢。做出了这些改变。 –