#include <QScopedArrayPointer>
#include <QDebug>
#include <stdexcept>
class MyData{
public:
MyData() {
qDebug() << "Construct a data";
}
~MyData() {
qDebug() << "Delete a data";
}
private:
float internal_data_;
};
class MyClass{
QScopedArrayPointer<MyData> data_;
public:
MyClass(){
data_.reset(new MyData[10]);
throw std::runtime_error("Shit happens");
}
};
int main(int argc, char *argv[])
{
MyClass a_class;
return 1;
}
运行此程序将输出:
Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
terminate called after throwing an instance of 'std::runtime_error'
what(): Shit happens
The program has unexpectedly finished.
在runtime_error之前,已完全创建变量data_。为什么没有调用data_析构函数?
另外,在这种情况下,如何确保内存不泄漏?
答案 0 :(得分:2)
我认为问题在于您的异常未被捕获并且正由终止处理程序处理。由于没有catch
来处理异常,因此编译器无法知道要“展开”多少。如果捕获异常,则会发生破坏。如果你愿意,你当然可以重新抛出它,例如:
#include <QScopedArrayPointer>
#include <QDebug>
#include <stdexcept>
class MyData{
public:
MyData() {
qDebug() << "Construct a data";
}
~MyData() {
qDebug() << "Delete a data";
}
private:
float internal_data_;
};
class MyClass{
QScopedArrayPointer<MyData> data_;
public:
MyClass(){
data_.reset(new MyData[10]);
throw std::runtime_error("Shit happens");
}
};
int main(int argc, char *argv[]) {
try {
MyClass a_class;
} catch (const std::runtime_error &) {
throw;
}
}
输出以下内容:
$ ./test2
Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
Delete a data
Delete a data
Delete a data
Delete a data
Delete a data
Delete a data
Delete a data
Delete a data
Delete a data
Delete a data
terminate called after throwing an instance of 'std::runtime_error'
what(): Shit happens
Aborted