c++language-lawyerstandard-layout

Using standard layout types to communicate with other languages


This draft of the standard contains a note at 11.2.6 regarding standard layout types :

[Note 3: Standard-layout classes are useful for communicating with code written in other programming languages. Their layout is specified in [class.mem]. — end note]

Following the link to class.mem we find rules regarding the layout of standard-layout types starting here but it is not clear to me what about them makes them useful for communicating with other languages. It all seems to be about layout-compatible types and common initial sequence, but I see no indication that these compatibility requirements extend being a given implementation.

I always assumed that standard layout types could not have arbitrary padding imposed by an implementation and had to follow an "intuitive" layout which would make them easy to use from other languages. But I can't seem to find any such rules.

What does this note mean? Did I miss any rules that force standard layout types to at least be consistent across a given platform?


Solution

  • The standard can’t meaningfully speak about other languages and implementations: even if one could unambiguously define “platform”, all it can do is constrain a C++ implementation, possibly in a fashion that would be impossible to satisfy for whatever arbitrary choices that other software makes. That said, the ABI can define such things, and standard-layout types are those that don’t have anything “C++-specific” (like references, base class subobjects, or a virtual table pointer) that would presumably fail to map into some other environment. In practice that “other environment” is just C, or some other language that itself follows C rules (e.g., ctypes in Python).