user997112
user997112

Reputation: 30615

What is the C++ memory layout of objects/structs etc?

In C++ I presume the C++ standard has nothing to do with how data members are arranged within a class, in terms of memory layout? Would I be right in thinking this is down to the compiler in question?

I'm very interested in learning how objects and other C++ entities (structs etc) are represented in physical memory (I know things like lists are node to node and arrays are continuous memory- but all the other aspects to the language).

EDIT: Would learning x86 assembler help with this and understanding C++ better?

Upvotes: 3

Views: 3193

Answers (2)

Stack Overflow is garbage
Stack Overflow is garbage

Reputation: 247969

The C++ standard does specify a few things, but far from everything.

The main rules are these:

  • objects in an array are laid out contiguously, with no padding between them.
  • class member objects not separated by an access specifier (public:/private:/protected:) are laid out in memory in the order in which they're declared, but there may be an unspecified amount of padding between member objects.
  • for certain types (standard-layout structs, in standardese terminology), the first base class, or if none exists, the first member, is laid out at the same address that the class itself.

There are a few more bits and pieces specified by the standard, but on the whole, the remaining details are really down to the compiler.

Upvotes: 6

Asha
Asha

Reputation: 11232

Yes, the standard doesn't say how the objects are to be represented in memory. To get an idea how normall C++ objects are represented read this book: inside C++ object model.

Upvotes: 1

Related Questions