gpt4 book ai didi

C++ 如何在不尝试 {} finally{} 的情况下安全地关闭文件?

转载 作者:行者123 更新时间:2023-11-28 00:30:55 25 4
gpt4 key购买 nike

假设有这样一个类:

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++ 上执行此操作?

最佳答案

通常的解决方案是使用 RAII:在这种情况下,例如,如果QFile 有一个“正确的”析构函数,只需将其声明为本地变量应该可以解决问题:

void A::doSomething()
{
QFile file;
file.open(...);
// ...
file.close(); // So you can check that everything when right.
}

QFile 被调用时,文件应该自动关闭破坏了,尽管如果之前没有关闭,你就不会能够检查状态(并且文件中的数据可能是不完整)。

如果出于某种原因这不可行,您可能想使用范围包装类:

class QFileWrapper
{
QFile* myFile;
public:
QFileWrapper( QFile* file ) : myFile( file ) {}
~QFileWrapper() { myFile->close(); }
};

我实际上为 std::ofstream 做了很多,使用 commit函数,它是采用文件名的构造函数,并打开。 commit 函数关闭文件,并且如果关闭成功,则设置一个标志,表明该文件已被关闭坚定的。析构函数测试标志,如果文件还没有提交,它会关闭它删除它,所以没有部分文件被遗弃。

关于C++ 如何在不尝试 {} finally{} 的情况下安全地关闭文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22964944/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com