Search code examples
c++visual-studioc++11visual-studio-2015

Force a C++ class to have non-aligned members


Consider this class:

class C3
{
public:
    uint16_t p1;
    uint16_t p2;
    uint8_t p3;
};

sizeof(C3) is 6. Is there any compiler routine to bypass alignment and force it's size to be 5? I tried to use alignas without success...


Solution

  • With the MSVC compiler (you have included the VS-2015 tag), you can use the #pragma pack directive to set padding options for classes and structures. This also allows you to save/restore 'default' settings, using the push and pop options.

    The following short example demonstrates this:

    #include <iostream>
    
    class C3 {
    public:
        uint16_t p1;
        uint16_t p2;
        uint8_t p3;
    };
    
    #pragma pack(push, 1) // Save current packing and set to single-byte
    class C4 {
    public:
        uint16_t p1;
        uint16_t p2;
        uint8_t p3;
    };
    #pragma pack(pop) // Restore saved packing
    
    class C5 {
    public:
        uint16_t p1;
        uint16_t p2;
        uint8_t p3;
    };
    
    int main()
    {
        std::cout << sizeof(C3) << std::endl; // 6
        std::cout << sizeof(C4) << std::endl; // 5
        std::cout << sizeof(C5) << std::endl; // 6 (again)
        return 0;
    }
    

    Many other compilers support directives equivalent to the MSVC #pragma pack.