C++ static_cast 向下转换有效性

标签 c++

<分区>

这个 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

关于C++ static_cast 向下转换有效性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47310700/

相关文章:

c++ - 内联汇编 : operand type mismatch for 'out'

c++ - Matlab编译成C++问题: fatal error C1083: Cannot open include file: 'windows.h'

c++ - 如何将 boost asio 接受器限制为本地主机和/或本地网络?

c++ - fstream 未创建文件名后附加了 asctime 值的文件

c++ - 如果我为多个编写器使用额外的互斥锁,我可以在 SQLite3 中使用 WAL 模式吗?

c++ - Borland 断言在 local_unwind() 中失败

来自其他类的 C++ 成员函数指针

c++ - 一般指针问题

c++ - 线程通信中消息队列相对于共享数据的优势是什么?

C++:使用多种条件验证字符串