c++ - 使用 auto_ptr<std::ofstream> 对象

标签 c++ auto-ptr

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

#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/

相关文章:

c# - 创建具有完全信任权限(包括网络权限)的托管 CLR AppDomain

c++ - 获取添加到子窗口的列表框控件中的文本

certificate - 使用 GnuTLS 导入证书期间出现错误代码 -207

c++ - 需要帮助调试我的第一个程序,Visual Studio 找不到 .exe 文件。

c++ - 在 C++03 中返回类似 `std::auto_ptr` 的集合的最佳方法是什么?

c++ - 这两个版本的代码有什么区别?

c++ - auto_ptr 的动态内存分配

c++ - 编译但失败的 C++ std::vector<std::auto_ptr<T>> 示例

c++ - 在没有 boost 和 c++0x 的情况下安全地进行类型删除

c++ - auto_ptr 内容的三元运算符不起作用