c++auto-ptr

Using auto_ptr<std::ofstream> object


I need to store my error and log messages to the file. This is the code sample:

#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(); // ???
}

If I defined cerrFile as a global variable, would be it released correctly? Need I close the log file before exit like with a regular pointer?


Solution

  • You don't need to close the file. When auto_ptr go out of scope call the destructor that close the file if not close.

    Annotation: Please avoid use of std::auto_ptr because is deprecated in c++11 and completely removed in c++17.