[英]Is it safe to call remove() to delete files in destructor?
我有一个类,在调用某些成员函数时会创建一些临时文件。 我希望每当类超出范围时(通常或由于异常)就删除这些文件,因此我想在析构函数中删除它们:
#include <cstdio>
#include <string>
class MyClass
{
//implementation details
//Names of temp files
std::string tempFile1, tempFile2,tempFile3;
~MyClass()
{
remove(tempFile1.c_str());
remove(tempFile2.c_str());
remove(tempFile3.c_str());
}
};
问题是,如果因异常而调用析构函数,则可能不是所有3个临时文件都已创建。 根据cpluscplus.com的说明 ,在这种情况下, remove()
函数将返回非零值并将某些内容写入stderr。 但是,由于它是C函数,因此不会有例外。
我知道破坏者不应该抛出。 这样的错误呢? 是否建议编写这样的析构函数?
您显示的内容可以正常工作。 但是我通常更喜欢RAII方法,例如:
#include <cstdio>
#include <string>
struct RemovableFile
{
std::string fileName;
bool canRemove;
RemovableFile() : canRemove(false) {}
~RemovableFile(){ if (canRemove) remove(fileName.c_str()); }
};
class MyClass
{
...
//Names of temp files
RemovableFile tempFile1, tempFile2, tempFile3;
...
};
void MyClass::doSomething()
{
...
tempFile1.fileName = ...;
...
if (file was created)
tempFile1.canRemove = true;
...
};
也许更像这样:
#include <cstdio>
#include <string>
#include <fstream>
struct RemovableFile
{
std::string fileName;
std::fstream file;
~RemovableFile() { if (file.is_open()) { file.close(); remove(fileName.c_str()); } }
void createFile(const std::string &aFileName)
{
file.open(aFileName.c_str(), ...);
fileName = aFileName;
}
};
class MyClass
{
...
//Names of temp files
RemovableFile tempFile1, tempFile2, tempFile3;
...
};
void MyClass::doSomething()
{
...
tempFile1.createFile(...);
...
};
C库函数remove
和C ++析构函数之间没有交互。
除非
您正在编写一个C库,并用C ++编写,上面的MyClass
是实现的一部分,因此调用remove
会触发一些不好的重入或其他操作。)
您是在信号处理程序中执行此操作的,该信号处理程序在调用C库的过程中关闭了,在这种情况下,C ++析构函数方面是没有实际意义的。 您不能从信号处理程序中调用remove
。
您会抛出跨C库激活框架的异常。 那可能是不好的。
即使remove
功能失败,它肯定也不会打印任何内容。 您误解了cplusplus.com参考文本。 它指的是其代码示例,而不是功能。 代码示例是打印消息的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.