2

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?

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
Yury Finchenko
  • 1,035
  • 13
  • 19
  • 7
    Don't use `auto_ptr`, which never really worked right and is deprecated. Use `std::unique_ptr`, which replaces it. – aschepler Dec 18 '19 at 05:53
  • 1
    `auto_ptr` has been deprecated since C++11 and was removed from the standard library in C++17. Since C++11 there is `std::unique_ptr` replacing it and before it you are probably better of with `boost::scoped_ptr` or some other boost smart pointer (or yet better by upgrading to a recent C++ version). – walnut Dec 18 '19 at 06:19
  • 3
    You also don't need a pointer here at all, from what I can tell. Just declare `std::ofstream a;` and use `a = std::ofstream(...); `, which also works since C++11 or `a.open(...)` which always worked. – walnut Dec 18 '19 at 06:23

2 Answers2

1

In your sample, you don't need to close the file.

When auto_ptr<std::ofstream> cerrFile; goes out of scope, the destructor of the contained object will be called. In this case, the destructor of std::ofstream which will close the file.

foolo
  • 804
  • 12
  • 22
1

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.

Zig Razor
  • 3,381
  • 2
  • 15
  • 35