这个 static_cast
向下转换有效吗?
// non-virtual, may be non-trivially copyable
struct Base{
int m_object;
};
// Derived class have only non-virtual functions
struct A : Base{
void arggh(){
std::cout << "Arrghh " << m_object;
}
};
int main() {
Base base{190};
A& a = static_cast<A&>(base);
a.arggh();
return 0;
}
我的意思是,创建基类,然后转换为派生类。
Live
static_cast
执行向下转换不执行任何安全检查。因为有可能 Base&
引用 A
的一个实例,转换继续进行,因为它不是实际上引用了 A
,我们进入未定义的行为领域*。
A dynamic_cast
另一方面更安全。它会执行检查并在引用转换的情况下抛出异常,或者返回 nullptr
。在指针转换的情况下†。
但是,由于您的基类缺少任何虚函数,dynamic_cast
是不可能的,所以你至少需要用一个虚拟析构函数来修改它:
class Base{
public:
int m_object;
virtual ~Base()=default;
};
现在如果我们尝试转换:
A* a = dynamic_cast<A*>(&base);
if (a)
a->arggh();
else
std::cout << "null\n";
我们的输出是
null
*相关标准语可以在[expr.static.cast]中找到:
[for a cast like static_cast<D&>(b)
where b
is an instance of a base class for D
], If the object of type “cv1 B
” is actually a base class subobject of an object of type D
, the result refers to the enclosing object of type D
. Otherwise, the behavior is undefined.
†[expr.dynamic.cast] 中的相关标准
The value of a failed cast to pointer type is the null pointer value of the required result type. A failed cast to reference type throws an exception of a type that would match a handler of type
std::bad_cast