开发者

Getting the size of member variable

If there is a POD structure, with some member variables, for example like this:

struct foo
{
   short a;
   int b;
   char c[50];
   // ...
};

Is there a way to get the size of a member variable in bytes, without creating an object of this type?

I know that this will work:

foo fooObj;
std::cout << sizeof( fooObj.a ) << std::endl;
std::cout << sizeof( fooObj.b ) << std::endl;
std::cout &l开发者_运维知识库t;< sizeof( fooObj.c ) << std::endl;

Would the following be optimized by the compiler and prevent the construction of an object?

std::cout << sizeof( foo().a ) << std::endl;


You can do that in C++0x:

sizeof(foo::a);


5.3.3/1:

The sizeof operator yields the number of bytes in the object representation of its operand. The operand is either an expression, which is not evaluated, or a parenthesized type-id.

The above means the following construct is well defined:

sizeof( ((foo *) 0)->a);


Use this form: sizeof(foo::a) instead.


Use the obvious:

sizeof( foo::a )

In C++, sizeof is ALWAYS evaluated at compile time, so there is no runtime cost whatsoever.


C++-0x allows you to do this:

  std::cout << sizeof( foo::a ) << std::endl;
  std::cout << sizeof( foo::b ) << std::endl;
  std::cout << sizeof( foo::c ) << std::endl;

C++-0x allows sizeof to work on members of classes without an explicit object.

The paper is here: Extending sizeof to apply to non-static data members without an object (revision 1)

I saw the post about this above too late. Sorry.


You can create macro wrapper of what @Erik suggested as:

#define SIZE_OF_MEMBER(cls, member) sizeof( ((cls*)0)->member )

And then use it as:

cout << SIZE_OF_MEMBER(foo, c) << endl;

Output:

50

Demo : http://www.ideone.com/ZRiMe


struct foo
{
   short a;
   int b;
   char c[50];
   // ...
   static const size_t size_a = sizeof(a);
   static const size_t size_b = sizeof(b);
   static const size_t size_c = sizeof(c);
};

Usage:

foo::size_a
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜