在下面的代码中,结构的析构函数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";
}
}
Run Code Online (Sandbox Code Playgroud)
就这样做吧
void test_file_open() {
FileWrapper fw("./fw-capture.dat");
Run Code Online (Sandbox Code Playgroud)
您正在创建一个额外的对象.
| 归档时间: |
|
| 查看次数: |
103 次 |
| 最近记录: |