#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;
}
Running this program will output:
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.
Right before the runtime_error, the variable data_ has been fully created. Why is it that data_ destructor not called?
Also, how do I make sure memory does not leak in this case?