Is it possible to determine the size of a C++ class at compile-time?
I seem to remember a template meta-programming method, but I could be mistaken...
sorry for not being clearer - I want the size to be printed in the build output window
sizeof is evaluated at compile time, but if the executable is moved to a machine where the compile time and runtime values would be different, the executable will not be valid.
You can check the size during compilation: static_assert (sizeof(mystruct) == 1024, "Size is not correct"); You need C++11 for that.
If you create it as a local variable, and specify a length, then it matters because the compiler needs to know how much space to allocate on the stack for the elements of the array. If you don't specify a size of the array, then it doesn't know how much space to set aside for the array elements.
C++ doesn't actually store the metadata for objects at runtime so size checking must be compile time. For an example of how C++ doesn't validate size, declare an array of int of some arbitrary size and read past the end of it.
If you really need to to get sizeof(X) in the compiler output, you can use it as a parameter for an incomplete template type:
template<int s> struct Wow; struct foo { int a,b; }; Wow<sizeof(foo)> wow; $ g++ -c test.cpp test.cpp:5: error: aggregate ‘Wow<8> wow’ has incomplete type and cannot be defined
To answer the updated question -- this may be overkill, but it will print out the sizes of your classes at compile time. There is an undocumented command-line switch in the Visual C++ compiler which will display the complete layouts of classes, including their sizes:
That switch is /d1reportSingleClassLayoutXXX, where XXX performs substring matches against the class name.
https://devblogs.microsoft.com/cppblog/diagnosing-hidden-odr-violations-in-visual-c-and-fixing-lnk2022/
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