Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

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

like image 219
Antonio Avatar asked Oct 17 '25 22:10

Antonio


2 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.

like image 95
WhozCraig Avatar answered Oct 19 '25 12:10

WhozCraig


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).

like image 32
geza Avatar answered Oct 19 '25 13:10

geza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!