可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
In C/C++, how do I determine the size of the member variable to a structure without needing to define a dummy variable of that structure type? Here's an example of how to do it wrong, but shows the intent:
typedef struct myStruct { int x[10]; int y; } myStruct_t; const size_t sizeof_MyStruct_x = sizeof(myStruct_t.x); // error
For reference, this should be how to find the size of 'x' if you first define a dummy variable:
myStruct_t dummyStructVar; const size_t sizeof_MyStruct_x = sizeof(dummyStructVar.x);
However, I'm hoping to avoid having to create a dummy variable just to get the size of 'x'. I think there's a clever way to recast 0 as a myStruct_t to help find the size of member variable 'x', but it's been long enough that I've forgotten the details, and can't seem to get a good Google search on this. Do you know?
Thanks!
回答1:
In C++ (which is what the tags say), your "dummy variable" code can be replaced with:
sizeof myStruct_t().x;
No myStruct_t object will be created: the compiler only works out the static type of sizeof's operand, it doesn't execute the expression.
This works in C, and in C++ is better because it also works for classes without an accessible no-args constructor:
sizeof ((myStruct_t *)0)->x
回答2:
I'm using following macro:
#include <iostream> #define DIM_FIELD(struct_type, field) (sizeof( ((struct_type*)0)->field )) int main() { struct ABC { int a; char b; double c; }; std::cout << "ABC::a=" << DIM_FIELD(ABC, a) << " ABC::c=" << DIM_FIELD(ABC, c) << std::endl; return 0; }
Trick is treating 0 as pointer to your struct. This is resolved at compile time so it safe.
回答3:
You can easily do
sizeof(myStruct().x)
As sizeof parameter is never executed, you'll not really create that object.
回答4:
Any of these should work:
sizeof(myStruct_t().x;);
or
myStruct_t *tempPtr = NULL; sizeof(tempPtr->x)
or
sizeof(((myStruct_t *)NULL)->x);
Because sizeof
is evaluated at compile-time, not run-time, you won't have a problem dereferencing a NULL pointer.
回答5:
In C++11, this can be done with sizeof(myStruct_t::x)
. C++11 also adds std::declval, which can be used for this (among other things):
#include <utility> typedef struct myStruct { int x[10]; int y; } myStruct_t; const std::size_t sizeof_MyStruct_x_normal = sizeof(myStruct_t::x); const std::size_t sizeof_MyStruct_x_declval = sizeof(std::declval<myStruct_t>().x);
回答6:
From my utility macros header:
#define FIELD_SIZE(type, field) (sizeof(((type *)0)->field))
invoked like so:
FIELD_SIZE(myStruct_t, x);