简体   繁体   English

结构析构函数被隐式调用-我的语法错误吗?

[英]Struct destructor called implicitly - is my syntax wrong?

In the following code, the destructor of the struct FileWrapper is called by the program without me explicitly asking for it. 在下面的代码中,程序不调用结构FileWrapper的析构函数,而无需我明确要求它。 How can I prevent this? 我该如何预防?

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";
    }
}

Just do this 做这个

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

You are creating an extra object. 您正在创建一个额外的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM