Can you explicitly set the structure / alignment of the structure in C ++, as you can in C #?

In C #, you have good alignment attributes, such as:

[StructLayout(LayoutKind.Explicit)]
public struct Message
{
    [FieldOffset(0)]
    public int a;
    [FieldOffset(4)]
    public short b;
    [FieldOffset(6)]
    public int c;
    [FieldOffset(22)] //Leave some empty space just for the heck of it.
    public DateTime dt;

}

Which gives you great control over how you need your structure laid out in memory. Is there such a thing in standard C ++?

+3
source share
4 answers

Compilers usually support this with #pragma, but this is not something that is included in the C ++ standard and therefore not portable.

For an example with the Microsoft compiler, see: http://msdn.microsoft.com/en-us/library/2e70t5y1(VS.80).aspx

+4
source

Hmya, : #, , . [FieldOffset] .

, :

#pragma pack(push, 1)
public struct Message
{
    int a;
    short b;
    int c;
    char padding1[12];
    long long dt;
}
#pragma pack(pop)
+4
+1

#, , C ( C) " ".

0

Source: https://habr.com/ru/post/1748232/


All Articles