Does adding a static constexpr member change the memory mapping of a struct/class?

Viewed 524

Note: This question arised in the context of shared memory between a C++ and C# program.

In C++11, does adding a static constexpr member change anything in term of memory mapping? I would intuitively say that a static constexpr member doesn't occupy any memory, but I suppose I am ignoring some very fundamental aspect, like polymorphism for example...

So, in the following example, are an instance of Dummy and an instance of Dummy2 guaranteed to occupy the same amount of memory?

struct Dummy {
  static constexpr std::size_t kSize = 512;
  char data[kSize];
};


static constexpr std::size_t kSize2 = 512;
struct Dummy2 {
  char data[kSize2];
};

In this test this theory is not disproved, but I am very far from being able to say that this is guaranteed.

int main() {
    std::cout << sizeof(Dummy) << " " << sizeof(Dummy2) << std::endl;
}

512 512

3 Answers

Per the language standard,

9.4.2 Static data members [class.static.data]

  1. A static data member is not part of the subobjects of a class. If a static data member is declared thread_- local there is one copy of the member per thread. If a static data member is not declared thread_local there is one copy of the data member that is shared by all the objects of the class.

emphasis mine.

It doesn't matter whether it is constexpr or not; it's static, and as such is not part of instance composition.

Dummy and Dummy2 are layout-compatible (static members don't matter), see class.mem/23.

However, the standard doesn't define what exact properties layout-compatible types have (it only defines when two types are layout-compatible, but doesn't say anything about the consequences). The intention must be that they have the same layout in memory, so you can assume that sizeof(Dummy) equals to sizeof(Dummy2).

The language definition puts a few constraints on object layout, but within those constraints, the compiler has a great deal of leeway. The language definition does not require the layout to change when you add a static member, and it doesn’t prohibit it from changing. There’s no obvious reason for changing the layout, but there is no absolute answer. It probably won’t change, but if it really matters, try it and see.

Related