简体   繁体   English

使用dynamic_pointer_cast时出现细分错误

[英]Segmentation fault when using dynamic_pointer_cast

The following code-snippet is a MWE of an issue I'm encountering with std::dynamic_pointer_cast : 以下代码段是我在std::dynamic_pointer_cast遇到的问题的MWE:

#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;
}

This program segfaults at the output stream line ( std::cout << ... ) presumably because the dynamic_pointer_cast is resulting in a nullptr , but I'm not sure why this is the case? 该程序在输出流行( std::cout << ... )发生段错误,大概是因为dynamic_pointer_cast导致了nullptr ,但是我不确定为什么会这样吗?

Any assistance is appreciated, plus here is a Coliru link to the snippet too . 感谢您提供任何帮助,此外,这也是该片段Coliru链接

This is expected behavior. 这是预期的行为。 fptr manages a pointer which pointing to a foo in fact. fptr管理实际上指向foo的指针。 When you down-cast it to pointer to bar via dynamic_cast the cast would fail and you'll get a null pointer. 当您通过dynamic_cast将其向下投影到bar指针时,转换将失败,并且您将获得一个空指针。

If fptr points to a bar then it'll work. 如果fptr指向bar那就可以了。 eg 例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM