在维基百科上的文件I / O的RAII的典型示例中,吞下关闭文件时发生的任何错误:
#include <iostream>
#include <string>
#include <fstream>
#include <stdexcept>
void write_to_file (const std::string & message) {
// try to open file
std::ofstream file("example.txt");
if (!file.is_open())
throw std::runtime_error("unable to open file");
// write message to file
file << message << std::endl;
// file will be closed when leaving scope (regardless of exception)
}
似乎无法确定file
自动关闭时是否发生错误;显然,只有file.rdstate()
在范围内时才能调用file
。
我可以手动调用file.close()
然后检查错误,但是我必须在从范围返回的每个地方都这样做,这违背了RAII的目的。
有些人评论说,在析构函数中只能发生文件系统损坏等不可恢复的错误,但我不相信这是真的,因为析构函数的AFAIK在关闭文件之前会刷新文件,并且可能发生可恢复的错误在冲洗的时候。
有没有一种常见的RAII方法来获取破坏期间发生的错误?我读到,从析构函数中抛出异常是危险的,因此听起来并不像正确的方法。
我能想到的最简单的方法是注册一个回调函数,如果在破坏期间发生任何错误,析构函数将调用该函数。令人惊讶的是,ios_base::register_callback
支持的事件似乎并不存在。这似乎是一个重大的疏忽,除非我误解了什么。
但也许回调是在现代课程设计中被破坏时通知错误的最常见方式?
我假设在析构函数中调用任意函数也很危险,但是将调用包装在try/catch
块中是完全安全的。
答案 0 :(得分:4)
您可以部分处理析构函数失败的情况:
class Foo {
public:
Foo() : count(std::uncaught_exceptions()) {}
~Foo() noexcept(false)
{
if (std::uncaught_exceptions() != count) {
// ~Foo() called during stack unwinding
// Cannot throw exception safely.
} else {
// ~Foo() called normally
// Can throw exception
}
}
private:
int count;
};
答案 1 :(得分:2)
如果您在展开时有特定代码处理文件闭包中的任何错误,您可以添加另一个抽象级别...
class MyFileHandler {
std::ofstream& f_;
public:
MyFileHandler(std::ofstream& f) : f_(f) {}
~MyFileHandler() {
f_.close();
// handle errors as required...
}
// copy and assignments elided for brevity, but should well be deleted
};
void write_to_file (const std::string & message) {
// try to open file
std::ofstream file("example.txt");
MyFileHandler fileCloser(file);
if (!file.is_open())
throw std::runtime_error("unable to open file");
// write message to file
file << message << std::endl;
// file will be closed when leaving scope (regardless of exception)
}
根据您的使用案例,您可以在课程中嵌入std::ofstream
。