Getting the size of member variable

前端 未结 7 388
猫巷女王i
猫巷女王i 2020-12-15 17:34

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

struct foo
{
   short a;
   int b;
   char c[50];
   // ...
};
相关标签:
7条回答
  • 2020-12-15 18:03

    Use the obvious:

    sizeof( foo::a )
    

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

    0 讨论(0)
  • 2020-12-15 18:05

    You can do that in C++0x:

    sizeof(foo::a);
    
    0 讨论(0)
  • 2020-12-15 18:15

    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.

    0 讨论(0)
  • 2020-12-15 18:18

    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);
    
    0 讨论(0)
  • 2020-12-15 18:20

    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

    0 讨论(0)
  • 2020-12-15 18:23
    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 讨论(0)
提交回复
热议问题