【发布时间】:2014-10-26 19:12:35
【问题描述】:
为什么 C++ 标准库流使用与对象生命周期分离的open()/close() 语义?在销毁时关闭可能在技术上仍会使类成为 RAII,但获取/释放独立性会在句柄可以指向任何内容但仍需要运行时检查才能捕获的范围中留下漏洞。
为什么库设计者选择他们的方法而不是只在引发失败的构造函数中打开?
void foo() {
std::ofstream ofs;
ofs << "Can't do this!\n"; // XXX
ofs.open("foo.txt");
// Safe access requires explicit checking after open().
if (ofs) {
// Other calls still need checks but must be shielded by an initial one.
}
ofs.close();
ofs << "Whoops!\n"; // XXX
}
// This approach would seem better IMO:
void bar() {
std_raii::ofstream ofs("foo.txt"); // throw on failure and catch wherever
// do whatever, then close ofs on destruction ...
}
这个问题的更好措辞可能是为什么访问未打开的fstream 值得拥有。通过句柄生命周期控制打开文件的持续时间在我看来根本不是一种负担,但实际上是一种安全优势。
【问题讨论】:
-
是的,它肯定缺少
throw_exception模式值。可以为后面的操作设置异常,但抛出构造函数会更好。
标签: c++ iostream raii c++-standard-library