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
Per the language standard,
9.4.2 Static data members [class.static.data]
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With