protocol-buffersprotobuf-c

Order of protobuf members in C/C++


I generate a Protocol Buffers3 message via:

message M
{
    uint32 first = 1;
    unint64 second = 2;
}

The generated .h header however has effectively this order:

struct M
{
    std::uint64_t second{};
    std::uint32_t first{};
}

Is there no guarantee on the ordering?


Solution

  • The order of the members in the message definition and the generated C++ header file is not guaranteed to be the same in Protobuf.

    This is because the Protocol Buffers compiler optimizes the generated code for efficiency and performance, and the order of the fields may be rearranged to achieve better memory layout and access patterns.

    Thus you should never depend on the order of member variables, for example in an initializer list:

    const M m_instance{1.,0.};  //  Which is which now?