以下代码片段是我遇到的问题的 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/