When I declare such a structure:
#pragma pack(1)
structure MyStruct{
uint32_t first;
uint8_t second;
};
#pragma pack()
I obviously wish it will take 5 bytes of memory. How will then such a vector behaves:
std::vector<MyStruct> MyVec;
Or such a map:
std::map<MyStruct> MyMap;
Will they obey requested alignment? Can I force STL structures to do that?
With the proviso that some compiler could ignore the #pragma completely, yes, the #pragma affects the definition of the type, so storing that type in a vector (for example) means what's stored will be packed.
#include <iostream>
#include <vector>
typedef unsigned long uint32_t;
typedef unsigned char uint8_t;
struct MyStruct0{
uint32_t first;
uint8_t second;
};
#pragma pack(1)
struct MyStruct{
uint32_t first;
uint8_t second;
};
#pragma pack()
int main(){
std::vector<MyStruct0> a;
std::vector<MyStruct> b;
std::cout << "Unpacked size: " << sizeof(a[0]) << "\n";
std::cout << "Packed size: " << sizeof(b[0]) << "\n";
return 0;
}
Result:
Unpacked size: 8
Packed size: 5
std::vector is required to be layout-compatible with plain C=style array of the same type. So it has no choice but place them at the size you managed for the struct.
For other, node-based collections it is up to the implementation how the nodes are created, what extra bytes appear there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With