Should static_castlt;Derived *gt;(Base pointer) give compile time error?(static_castlt;Derived *gt;(Base pointer) 是否应该给出编译时错误?)
问题描述
static_cast(Base pointer) 是否应该给出编译时错误?
Should static_cast(Base pointer) give compile time error?
class A
{
public:
A()
{
}
};
class B : public A
{
public:
B()
{
}
};
int main()
{
A *a=new A();
B * b=static_cast<B*>(a); // Compile Error?
}
推荐答案
它不能给出编译时错误,因为 Base-Derived 关系可以在运行时存在,这取决于被转换的指针的地址.static_cast 总是成功,但如果你没有转换为正确的类型,将会引发 undefined-behavior.dynamic_cast 可能会失败,也可能不会,实际上是在告诉您是否尝试转换为正确的类型.
It cannot give compile time error because a Base-Derived relationship can exist at runtime depending on the address of the pointers being casted.
static_cast always succeeds, but will raise undefined-behavior if you don't cast to the right type. dynamic_cast may fail or not, actually telling you whether you tried to cast to the right type or not.
所以在我看来,static_cast 应该用于向下转换,前提是设计可以确定存在这种可能性.一个很好的例子是 CRTP.所以在某些情况下这是合乎逻辑的,但尽量避免它,因为它是未定义的行为.
So in my opinion, static_cast should be used to downcast only if the design can establish that such a possibility exists. One good example of this is CRTP. So it is logical in some situations but try to avoid it as it is undefined-behavior.
static_cast 不需要 RTTI,这可能使它理论上更快,但我会随时用 dynamic_cast 来抵消未定义的行为static_cast 可能导致!
RTTI is not needed for static_cast which might make it theoretically faster, but I will anytime trade-in a dynamic_cast against the undefined behavior that static_cast may cause!
这篇关于static_cast<Derived *>(Base pointer) 是否应该给出编译时错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:static_cast<Derived *>(Base pointer) 是否应该给出编译时错误?
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
