简体   繁体   中英

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. Rather, it's a declaration of a function taking no parameters and returning MyClass . See also: most vexing parse

MyClass graph2(3); does create an instance of MyClass . Its constructor leaves myList pointer uninitialized, and then its destructor exhibits undefined behavior by way of accessing said uninitialized pointer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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