创建指针C时出现segfault

时间:2019-03-28 18:43:26

标签: c++

在在线c ++编译器上编译时,出现Segmentation fault错误。 (引发错误的行将由代码中的注释指出)

#include <iostream>
#include <memory>

class A
{

};

class B:public A
{

};


using namespace std;
class Base
{
public:
    int b;
    std::shared_ptr<A> Display()
    {
        cout<<"Base: Non-virtual display."<<endl;
    };
    virtual void vDisplay()
    {
        cout<<"Base: Virtual display."<<endl;
    };
};

class Derived : public Base
{
public:
    int d;
    std::shared_ptr<B> Display()
    {
        cout<<"Derived: Non-virtual display."<<endl;
    };
    virtual void vDisplay()
    {
        cout<<"Derived: Virtual display."<<endl;
    };
};

int main()
{
    cout<<"Hello World"<<endl;
    Derived d;
    d.Display();

    Base *b = new Derived; // this line thorws the error
    b->vDisplay();
    return 0;
}

我有点困惑;如果我只是创建一个对象而不是指针,那很好。我在哪里弄错了?

1 个答案:

答案 0 :(得分:4)

错误实际上发生在上一行d.Display();上。控制流离开Derived::Display()函数而没有返回std::shared_ptr<B>导致未定义行为。

正如其他人所建议的那样,启用编译器警告和/或实际注意它们是一个好主意。这是一种罕见的情况,当编译器倾向于警告您的程序中可能存在未定义的行为时。