c++ - 隐式调用的结构析构函数 - 我的语法有误吗?

标签 c++ class struct

在下面的代码中,程序调用了结构FileWrapper 的析构函数,而我没有明确要求它。我怎样才能避免这种情况?

struct FileWrapper {
    std::fstream* capture_file;
    std::string filename;
    FileWrapper(std::string _filename = "./capture.dat", bool overwrite = true) {
        filename = _filename;

        std::ios_base::openmode mode = std::fstream::binary | std::fstream::in | std::fstream::out | std::fstream::trunc;

        capture_file = new std::fstream(filename, mode);
        if (!capture_file->is_open()) {
            std::cout << "Could not open capture file.\n";
        }
    }

    void close() {
        std::cout << "closing file.\n";
        capture_file->close();
    }

    ~FileWrapper() {
        close();
    }
};

void test_file_open() {
    FileWrapper fw = FileWrapper("./fw-capture.dat");
    //Odd behaviour: fw destructor called before or during the following line
    if (!fw.capture_file->is_open()) {
        std::cout << "File Wrapper's capture file is not open.\n";
    } else {
        std::cout << "File Wrapper's capture file IS open.\n";
    }
}

最佳答案

就这样

void test_file_open() {
    FileWrapper fw("./fw-capture.dat");

您正在创建一个额外的对象。

关于c++ - 隐式调用的结构析构函数 - 我的语法有误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21010893/

相关文章:

C++,函数重载问题

c++ - 如何用 QDBus 解析 {String 的字典,{String,Variant}} 的字典?

WordPress 上的 CSS

c# - 结构体 sizeof/Marshal.SizeOf 变化

c++ - 为什么拥有作业并在其他线程中等待它们会导致整个应用程序等待?

Python OOP问题,一个类的值没有被另一个类的函数更新

java - 在JAVA中实例化一个抽象类?

以星号结尾的 C 结构

c - 在其他文件中的结构/数组上使用 malloc

c++ - 在 int 中存储大于 INT_MAX 的数字