我需要将错误和日志消息存储到文件中。这是代码示例:
#include <fstream>
#include <iostream>
#include <memory>
int main()
{
std::auto_ptr<std::ofstream> cerrFile;
try {
std::ofstream* a;
a = new std::ofstream("c:\\Development\\_Projects\\CERR_LOG.txt");
cerrFile.reset(a);
a = NULL;
std::cout << cerrFile.get() << std::endl << a;
std::cerr.rdbuf(cerrFile->rdbuf());
}
catch (const std::exception& e) {
std::cerr << "error: " << e.what();
}
// ...
cerrFile.get()->close(); // ???
}
如果我将cerrFile
定义为全局变量,它会被正确释放吗?我需要像使用常规指针一样在退出之前关闭日志文件吗?
最佳答案
您不需要关闭该文件。当 auto_ptr 超出范围时,调用析构函数,如果未关闭则关闭文件。
注释: 请避免使用 std::auto_ptr,因为它在 c++11 中已弃用,并在 c++17 中完全删除。
关于c++ - 使用 auto_ptr<std::ofstream> 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59386177/