假设这样一个类:
class A {
private:
QFile file;
public:
A::A(QFile file): file(file) {}
void doSomething() {
file.open(QIODevice::WriteOnly);
// ... do operations that can throw an exception
file.close();
}
}
如果发生某些事情,close() 永远不会调用它。正确的是使用 try - finally,但 C++ 不支持它:
class A {
private:
QFile file;
public:
A::A(QFile file): file(file) {}
void doSomething() {
file.open(QIODevice::WriteOnly);
try {
// ... do operations that can throw an exception
}
finally {
file.close();
}
}
}
我怎样才能在 C++ 上做到这一点?