gpt4 book ai didi

c++ - 为什么 static_cast 在逻辑上应该出于安全目的拒绝它们或者 static_cast 与安全无关时允许向下转换?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:50:03 28 4
gpt4 key购买 nike

在下面的示例中,编译器接受 static_cast 向下转换,导致未定义的行为,而我认为 static_cast 完全是为了安全(C 风格转换无法提供) .

#include <iostream>

class Base {
public:
int x = 10;
};
class Derived1: public Base
{
public:
int y = 20;

};
class Derived2 : public Base
{
public:
int z = 30;
int w = 40;

};

int main() {

Derived1 d1;

Base* bp1 = static_cast<Base*>(&d1);
Derived2* dp1 = static_cast<Derived2*>(bp1);

std::cout << dp1->z << std::endl; // outputs 20
std::cout << dp1->w << std::endl; // outputs random value
}

最佳答案

dynamic_cast 只有在您不确定转换是否会成功并且捕获异常或检查 nullptr 时才真正使用。但是,如果您确定您的向下转型会成功,该语言允许您使用static_cast(它更便宜)。如果你错了,那是你的问题。在理想的世界中,每次施法都会在 100% 的时间内成功。但我们并不生活在一个理想的世界中。有点像数组下标。 arr[5] 表示“我绝对确定这个数组至少有 6 个元素。编译器不需要检查”。如果您的数组比您预期的要小,那又是您的问题。

关于c++ - 为什么 static_cast 在逻辑上应该出于安全目的拒绝它们或者 static_cast 与安全无关时允许向下转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55324915/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com