爲什麼需要這段代碼?使用限制結構尺寸:
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'嗎? –
謝謝。做出了這些改變。 –