c++ - 使用dynamic_pointer_cast时出现段错误

标签 c++ shared-ptr dynamic-cast

以下代码片段是我遇到的问题的 MWE std::dynamic_pointer_cast :

#include <iostream>
#include <memory>

class foo {
private:
    int x;
public:
    foo() : x(0) {}
    foo(int xx) : x(xx) {}
    virtual ~foo() = default;
    int get_x() const { return x; }
};

class bar : public foo {
private:
    double y;
public:
    bar(double yy) : foo(), y(yy) {}
    double get_y() const { return y; }
};

int main(void) {
    bar b(0.5);
    std::shared_ptr<foo> fptr = std::make_shared<foo>(b);
    std::cout << (std::dynamic_pointer_cast<bar>(fptr))->get_x();
    return 0;
}

该程序在输出流行 ( std::cout << ... ) 处出现段错误,大概是因为 dynamic_pointer_cast导致 nullptr ,但我不确定为什么会这样?

感谢任何帮助,此外还有 Coliru link to the snippet too .

最佳答案

这是预期的行为。 fptr 管理一个实际上指向 foo 的指针。当您通过dynamic_cast将其向下转换为指向bar的指针时,转换将失败并且您将得到一个空指针。

如果fptr指向一个bar那么它就会工作。例如

std::shared_ptr<foo> fptr = std::make_shared<bar>(b);

关于c++ - 使用dynamic_pointer_cast时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50558009/

相关文章:

c++ - 错误 C2228、错误 C2275

c++ - 从 Boost.Spirit.Qi 制作shared_ptr

c++ - 超出范围后在 Lambda 中设置共享指针

c++ - 来自两个抽象类的多重继承(Qt)

c++ - 继承和指向指针 : why doesn't it work and how do I get around it? 的指针

c++ - 如何在每次 QTimer 发射时使用 QLabel

c++ 以此类为类型继承类模板

c++ - std::tr1 中的 shared_ptr

c++ - 目标类不明确的 Dynamic_cast

c++ - 如何使用 LLVM 为不同的目标架构编译程序?