使用 dynamic_pointer_cast 时出现分段错误
Segmentation fault when using dynamic_pointer_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);
以下代码片段是我遇到的问题的 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);