Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get the size of a struct field w/o creating an instance of the struct?

Tags:

c++

sizeof

It's trivial to get the size of a struct's field in C++ if you have an instance of the struct. E.g. (uncompiled):

typedef struct Foo {     int bar;     bool baz; } Foo;  // ...  Foo s; StoreInSomething(s.bar, sizeof(s.bar)); // easy as pie 

Now I can still do something like this, but with the interface I'm implementing (I get a BOOL that indicates what the state of a specific bit in a bitfield should be), I'd be creating the struct solely to get the size of the data member. Is there a way to indicate to the compiler that it should use the size of a struct's field without creating an instance of the struct? It would be the philosophical equivalent of:

SetBit(bool val) {     StoreInSomething(         BITFIELD_POSITION_CONSTANT, // position of bit being set         val,                        // true = 1, false = 0         sizeof(Foo::bar));          // This is, of course, illegal.  (The method I've been told I must use req's the size of the target field.) } 

Creating the struct on the stack should be fast and cheap, but I suspect I'll get dinged for it in a code review, so I'm looking for a better way that doesn't introduce an add'l maintenance burden (such as #defines for sizes).

like image 940
Greg D Avatar asked Sep 15 '10 14:09

Greg D


People also ask

How do you determine the size of a struct byte?

If you want to manually count it, the size of a struct is just the size of each of its data members after accounting for alignment. There's no magic overhead bytes for a struct.

What is sizeof struct node?

if sizeof(double) is 8 byte then sizeof(struct node) should be 16 byte(as per first program).


1 Answers

You can use an expression such as:

sizeof Foo().bar 

As the argument of sizeof isn't evaluated, only its type, no temporary is actually created.


If Foo wasn't default constructible (unlike your example), you'd have to use a different expression such as one involving a pointer. (Thanks to Mike Seymour)

sizeof ((Foo*)0)->bar 
like image 154
CB Bailey Avatar answered Sep 18 '22 11:09

CB Bailey