【发布时间】:2021-02-20 07:00:06
【问题描述】:
我有一个带有析构函数的简单类。如果我使用默认构造函数从中实例化一个对象,则程序会成功终止,但如果我使用具有任何参数的构造函数对其进行实例化,则程序会失败。
#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;
}
【问题讨论】:
-
为什么
myList是一个指向 std::list 的指针?这是不寻常的,也是您的问题的原因。 -
delete myList- 但你从来没有new它! -
如果你想使用
myList作为指针,你的类还必须遵循 3 或 5 的规则,这比 0 的规则更有效。https://en.cppreference.com/w/cpp/language/rule_of_three -
从 C++11 开始,不要明确使用
new和delete。利用 RAII 模式并使用std::unique_ptr和std::shared_ptr。还有一个指向srd::list<int>的指针有点矫枉过正。 -
这是 UB(
deleteing 指针,你永远不会new),代码可以做任何事情,但我对这种特定行为感到惊讶。
标签: c++ destructor terminate