Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pragma pack an stl containers

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?

like image 319
Dejwi Avatar asked Dec 12 '25 21:12

Dejwi


2 Answers

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
like image 193
Jerry Coffin Avatar answered Dec 15 '25 10:12

Jerry Coffin


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.

like image 25
Balog Pal Avatar answered Dec 15 '25 11:12

Balog Pal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!