2

Is there a generic way (not platform dependent) to get at compile time the size of a class object in the memory, without counting the vtable pointers?

curiousguy
  • 8,038
  • 2
  • 40
  • 58
Reflection
  • 1,936
  • 3
  • 21
  • 39

2 Answers2

1

As you are asking for a portable way:

class MyClass
{
private:
  struct S 
  {
    DataMemberType1 dataMember1;
    ...
    DataMemberTypeN dataMemberN;
  } m;

public:
  static const size_t MemberSize = sizeof(S);
}; 
ur.
  • 2,890
  • 1
  • 18
  • 21
  • Are you sure this is 100% portable and `sizeof(MyClass) - sizeof(S)` will always be exactly equal to the size of the vpointer? – Neil Kirk Feb 10 '15 at 14:45
  • @Neil: My solution avoids the implementation specific details. Have a short look at "How are C++ objects laid out in memory?" [link](http://www.stroustrup.com/bs_faq2.html#layout-obj). – ur. Feb 10 '15 at 15:02
  • That doesn't answer my question.. what if there is padding? – Neil Kirk Feb 10 '15 at 15:05
  • @Neil: Yes, you can expect padding, but it should make no difference as you have the same padding in 'class' as in 'struct' – ur. Feb 10 '15 at 15:35
  • What about the padding present in MyClass but not in m? – Neil Kirk Feb 10 '15 at 15:41
0

Use sizeof on this class, it doesn't include size of the vtable just the pointer.

Paul Evans
  • 27,315
  • 3
  • 37
  • 54
  • @PaulEvans Your answer is false for any object that has virtual functions (any object actually containing a vtable.) http://ideone.com/7y48aO – Jonathan Mee Jul 14 '15 at 12:24
  • @JonathanMee The answer is correct; class instances contains a vptr (short for vtable pointer) **not** a vtable (table of function pointers for virtual functions of the class + RTTI info + virtual bases offset) – curiousguy Aug 01 '15 at 00:52