共用方式為


編譯器警告 (層級 1 和層級 4,關閉) C4437

dynamic_cast 從虛擬基地「base_class」到「derived_class」在某些情況下可能會失敗

備註

此警告預設為關閉。 如需詳細資訊,請參閱 Compiler Warnings That Are Off by Default

在下列情況中會使用dynamic_cast操作:

  • 轉換是從基底類別指標到衍生類別指標。
  • 衍生類別虛擬繼承基底類別。
  • 衍生類別沒有 vtordisp 虛擬基礎的欄位。
  • 類型轉換可在衍生類別的建構子或解構子中找到,或是在從衍生類別繼承的類別中找到。 否則,會發出編譯器警告 C4436,而不是 C4435。

此警告指出 套用至部分建構的物件時,可能 dynamic_cast 無法正確執行。 當從繼承自 derived_class 的類別的建構函式或解構函式呼叫封閉函式時,就會發生這種情況。 如果從未進一步衍生 derived_class ,或者在物件建構或終結期間未呼叫封閉函式,您可以忽略錯誤。

範例

下列範例會產生 C4437,並示範因遺漏 vtordisp 欄位而產生的程式碼產生問題:

// C4437.cpp
// To see the warning and runtime assert, compile with: /W4
// To eliminate the warning and assert, compile with: /W4 /vd2
//       or compile with: /W4 /DFIX
#pragma warning(default : 4437)
#include <cassert>

struct A
{
public:
    virtual ~A() {}
};

#if defined(FIX)
#pragma vtordisp(push, 2)
#endif
struct B : virtual A
{
    B()
    {
        func();
    }

    void func()
    {
        A* a = static_cast<A*>(this);
        B* b = dynamic_cast<B*>(a);     // C4437
        assert(this == b);              // assert unless compiled with /vd2
    }
};
#if defined(FIX)
#pragma vtordisp(pop)
#endif

struct C : B
{
    int i;
};

int main()
{
    C c;
}

另請參閱

dynamic_cast 運算子
vtordisp
編譯器警告 (層級 1) C4436