使用 auto_ptr<std::ofstream> 对象
Using auto_ptr<std::ofstream> object
我需要将错误和记录消息存储到文件中。这是代码示例:
#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
的析构函数将关闭文件。
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- CMake-按正确顺序将项目与C运行时对象文件链接
- 空基优化子对象的地址
- 将对象数组的引用传递给函数
- 你能重载对象变量名本身返回的内容吗
- fstream / ifstream / ofstream 对象如何转换为布尔值
- 使用 auto_ptr<std::ofstream> 对象
- 为什么我可以在临时 std::ofstream 对象上使用"operator<<"?
- 如何在共享指针向量中检查重复的"ofstream"对象
- 将 std::ofstream 对象作为参数传递给类方法
- 有效而干净的方法来编写一个ofstream/fstream对象,以用标头编写表
- Ofstream 对象不能使用运算符<<C++
- 在使用 ofstream 将数据写入其文件后更新 ifstream 对象
- ofstream-需要在close()操作后删除对象句柄
- 如果从终端终止程序,打开的ofstream对象会发生什么
- 可以使用ofstream对象作为backtrace_symbols_fd()的第三个参数吗?
- Ofstream不向文本文件写入对象
- c++的ofstream向文件写入值而不是对象的地址
- 如何正确传递ofstream对象?