我想知道基类是否可以检测(并做出反应)派生构造函数中抛出的异常。
在这个有点人为的示例中,我想避免在无法构造
Derived
实例时出现警告,因为用户无法关闭它。我可以将派生构造函数包装在 try/catch
块中,但我必须对每个派生构造函数都要求这样做。理想情况下,我想在基类本身中实现它。我已经找到了如何在派生类中捕获基类构造函数异常(如何在 C++ 中捕获基类构造函数异常?),但我想要与此相反的东西。
#include <iostream>
struct Base {
void close() {
closed = true;
}
~Base() {
if (!closed) std::cout << "Warning: I should be closed!" << std::endl;
}
private:
bool closed = false;
};
struct Derived : public Base {
Derived() : Base() {
throw 0;
}
};
int main() {
// Issues warning
Base not_closed;
// Issues no warning
Base().close();
// How can I prevent a warning here?
try {
Derived derived;
} catch (...) {
}
}
更新:一种替代方案可能是跳过调用
~Base
,但我知道这是不可能的。
您可以扭转逻辑以避免警告:
#include <iostream>
struct Base {
void close() {
closed = true;
}
void open() {
closed = false;
}
~Base() {
if (!closed) std::cout << "Warning: I should be closed!" << std::endl;
}
private:
bool closed = true;
};
struct Derived : public Base {
Derived() : Base() {
throw 0;
Base::open();
}
};
int main() {
// How can I prevent a warning here?
try {
Derived derived;
} catch (...) {
}
}
Base
初始化closed = true
,并且在构造Derived
时不会抛出异常,它会调用open()
。