本文介绍了在构造函数中使用object-expression调用虚函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

 c  
  • 否则, x 是包含 x 的(唯一)对象的完整对象。

    • If x is a complete object, then x is the complete object of x.
    • Otherwise, the complete object of x is the complete object of the (unique) object that contains x.

    实质上,你引用的句子使得 static_cast< C *>(this) - > foo(); in B 的构造函数未定义的行为,即使正在构造的完整对象是 C 。标准实际上提供了一个很好的例子:

    In essence, the sentence you cited makes doing static_cast<C*>(this)->foo(); in B's constructor undefined behavior in your code, even if the complete object being constructed is a C. The standard actually provides a pretty good example here:

    struct V {
        virtual void f();
        virtual void g();
    };
    struct A : virtual V {
        virtual void f();
    };
    struct B : virtual V {
        virtual void g();
        B(V*, A*);
    };
    
    struct D : A, B {
        virtual void f();
        virtual void g();
        D() : B((A*)this, this) { }
    };
    
    B::B(V* v, A* a) {
        f();    // calls V::f, not A::f
        g();    // calls B::g, not D::g
        v->g(); // v is base of B, the call is well-defined, calls B::g
        a->f(); // undefined behavior, a’s type not a base of B
    }
    

    可以已经:Ideone的编译器(GCC)实际调用 V :: f()在 a-> f(); 行,即使指针指的是完全构造的 A 子对象。

    In fact, you can already see the undefined behavior show up in this example if you run it: Ideone's compiler (GCC) actually calls V::f() on the a->f(); line, even though the pointer is referring to a fully constructed A subobject.

    这篇关于在构造函数中使用object-expression调用虚函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    08-18 13:53