使用 auto_ptr<std::ofstream> 对象

Using auto_ptr<std::ofstream> object

本文关键字:ofstream 对象 gt std lt auto ptr 使用      更新时间:2023-10-16

我需要将错误和记录消息存储到文件中。这是代码示例:

#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 中完全删除。

在示例中,无需关闭文件。

auto_ptr<std::ofstream> cerrFile;超出范围时,将调用所包含对象的析构函数。在这种情况下,std::ofstream的析构函数将关闭文件。