在下面的代码中,程序调用了结构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/