sizeof class with int , function, virtual function in C++?

前端 未结 5 1883
夕颜
夕颜 2020-11-29 21:39

This is an online C++ test question, which has been done.

#include
using namespace std; 
class A
{

};
class B
{
int i; 
}; 

class C
{
void         


        
5条回答
  •  天涯浪人
    2020-11-29 22:41

    why not try printing out the layout? From system V abi

    • dsize(O): the data size of an object, which is the size of O without tail padding.
    • nvsize(O): the non-virtual size of an object, which is the size of O without virtual bases.
    • nvalign(O): the non-virtual alignment of an object, which is the alignment of O without virtual bases.

    for example (put your code and remember to apply sizeof to the type you want to check)

    struct Base1 {
      virtual int method_base_11() {
        return 11;
      }
      virtual ~Base1() = default;
    };
    
    struct Base2 {
      virtual int method_base_21() {
        return 22;
      }
      virtual ~Base2() = default;
    };
    
    struct Foo: public Base1, public Base2 {
      int a;
    };
    
    int main() {
      Foo foo;
      foo.method_base_21();
      return sizeof(Foo);
    }
    

    output,

    $ clang -cc1 -std=c++11 -fdump-record-layouts foo.cc
    
    *** Dumping AST Record Layout
             0 | struct Base1
             0 |   (Base1 vtable pointer)
               | [sizeof=8, dsize=8, align=8,
               |  nvsize=8, nvalign=8]
    
    *** Dumping AST Record Layout
             0 | struct Base2
             0 |   (Base2 vtable pointer)
               | [sizeof=8, dsize=8, align=8,
               |  nvsize=8, nvalign=8]
    
    *** Dumping AST Record Layout
             0 | struct Foo
             0 |   struct Base1 (primary base)
             0 |     (Base1 vtable pointer)
             8 |   struct Base2 (base)
             8 |     (Base2 vtable pointer)
            16 |   int a
               | [sizeof=24, dsize=20, align=8,
               |  nvsize=20, nvalign=8]
    
    

提交回复
热议问题