调用remove()删除析构函数中的文件是否安全



我有一个类,当调用某些成员函数时,它会创建一些临时文件。每当类超出范围时(通常或由于异常),我希望删除这些文件,所以我想在析构函数中删除它们:

#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的参考文本。它指的是它的代码示例,而不是函数。代码示例是打印消息的内容。

最新更新