dynamic_cast在建構函式或解構函式中,從虛擬基底 'base_class' 到 'derived_class' 可能因物件部分建構而失敗。
備註
dynamic_cast在下列情況下會使用作業:
- 轉換是從基底類別指標到衍生類別指標。
- 衍生類別虛擬繼承基底類別。
- 衍生類別沒有
vtordisp虛擬基礎的欄位。 - 轉換可在衍生類別的建構函數或解構函式中找到,或繼承自衍生類別的類別。
此警告指出,如果將它 dynamic_cast 套用至部分建構的物件,則可能無法正確執行。 如果派生建構函式/解構函式正在某個進一步派生物件的子物件上運作,就會發生這種情況。 如果警告中指定的衍生類別未進一步衍生,您可以忽略警告。
範例
下列範例會產生 C4436,並示範因缺少 vtordisp 欄位而產生程式碼的問題:
// C4436.cpp
// To see the warning and runtime assert, compile with: /W1
// To eliminate the warning and assert, compile with: /W1 /vd2
// or compile with: /W1 /DFIX
#include <cassert>
struct A
{
public:
virtual ~A() {}
};
#if defined(FIX)
#pragma vtordisp(push, 2)
#endif
struct B : virtual A
{
B()
{
A* a = static_cast<A*>(this);
B* b = dynamic_cast<B*>(a); // C4436
assert(this == b); // asserts unless compiled with /vd2
}
};
#if defined(FIX)
#pragma vtordisp(pop)
#endif
struct C : B
{
int i;
};
int main()
{
C c;
}