简体   繁体   English

为什么这个非常简单的小 C++ 程序以 -1073741819 (0xC0000005) 终止?

[英]Why does this very simple and little C++ program terminates with -1073741819 (0xC0000005)?

I have a simple class with a destructor.我有一个带有析构函数的简单类。 If I instantiate an object from it with default constructor, then the program terminates succesfully, but if I instantiate it with a constructor that has any parameter, it terminates unsuccesfully.如果我使用默认构造函数从它实例化一个对象,那么程序会成功终止,但是如果我使用具有任何参数的构造函数实例化它,它会失败终止。

#include <iostream>
#include <list>

class MyClass {
public:
    std::list<int>* myList;
    MyClass();
    MyClass(int a);
    ~MyClass();
};

MyClass::MyClass() {}
MyClass::MyClass(int a) {}
MyClass::~MyClass() { delete myList; }

int main()
{

    // If I do only this, the program terminates succesfully with 0 as return value
    MyClass graph1();

    // But if I do this, the program terminates unsuccesfully
    MyClass graph2(3);

    return 0;
}

MyClass graph1(); doesn't create an instance of MyClass , whether initialized with the default constructor or otherwise.不创建MyClass的实例,无论是使用默认构造函数还是其他方式初始化。 Rather, it's a declaration of a function taking no parameters and returning MyClass .相反,它是一个不带参数并返回MyClass的函数的声明。 See also: most vexing parse另见:最烦人的解析

MyClass graph2(3); does create an instance of MyClass .确实创建了MyClass一个实例。 Its constructor leaves myList pointer uninitialized, and then its destructor exhibits undefined behavior by way of accessing said uninitialized pointer.它的构造函数使myList指针未初始化,然后它的析构函数通过访问未初始化的指针表现出未定义的行为。

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

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