Is there any penalty/cost of virtual inheritance in C++, when calling non-virtual base method?

前端 未结 7 1905
耶瑟儿~
耶瑟儿~ 2020-12-18 18:13

Does using virtual inheritance in C++ have a runtime penalty in compiled code, when we call a regular function member from its base class? Sample code:



        
相关标签:
7条回答
  • 2020-12-18 19:03

    There has to be a cost to virtual-inheritance.

    The proof is that virtually inherited classes occupy more than the sum of the parts.

    Typical case:

    struct A{double a;};
    
    struct B1 : virtual A{double b1;};
    struct B2 : virtual A{double b2;};
    
    struct C : virtual B1, virtual B2{double c;}; // I think these virtuals are not strictly necessary
    
    static_assert( sizeof(A) == sizeof(double) ); // as expected
    
    static_assert( sizeof(B1) > sizeof(A) + sizeof(double) ); // the equality holds for non-virtual inheritance
    static_assert( sizeof(B2) > sizeof(A) + sizeof(double) );  // the equality holds for non-virtual inheritance
    
    static_assert( sizeof(C) > sizeof(A) + sizeof(double) + sizeof(double) + sizeof(double) );
    static_assert( sizeof(C) > sizeof(A) + sizeof(double) + sizeof(double) + sizeof(double) + sizeof(double));
    

    (https://godbolt.org/z/zTcfoY)

    What is stored additionally? I don't exactly understand. I think it is something like a virtual table but for accessing individual members.

    0 讨论(0)
提交回复
热议问题