Wed
08
Jul 2015
Today I wanted to know what is sizeof(SomeStructure) during my coding in C++ in Visual Studio, without compiling and running my program. I needed that to put it into an assertion. Sure I could run the program and then break into debugger and evaluate the sizeof(SomeStructure) e.g. in Watches window, but the project is big and takes long time to build.
It turns out there is no such feature in Visual Studio to check size of structure, but it can be easily hacked using IntelliSense. In just few seconds, from this Google query, through its first result - this StackOverflow page, I have found following solution:
1. Put this line somewhere into your code:
template<size_t S> class Sizer { }; Sizer<sizeof(MY_STRUCTURE)> foo;
2. Replace "MY_STRUCTURE" with the name of your structure, other type or a variable.
3. Hover mouse cursor over "foo" and observe evaluated expression, for example: "Sizer<1296U> foo". 1296 is the size of your structure, in bytes - same as operator sizeof would return in runtime, when your program is compiled in currently selected configuration. "U" is for "unsigned".
By the way, maybe it would be a good feature request to add printing size of a type to the information available in design-time in Visual Studio, e.g. to Properties window, where there already are information about the type like IsTemplate, IsValue etc.?
Comments | #c++ #visual studio Share