escapecharacter
escapecharacter

Reputation: 965

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

Upvotes: 0

Views: 125

Answers (1)

Gary
Gary

Reputation: 5732

Just do this

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

You are creating an extra object.

Upvotes: 5

Related Questions