NOhs
NOhs

Reputation: 2830

C++: How to get rid of lazy initialization

To log errors I have the following code that can be called:

void writeErrorToLog(const LogMessage& message)
    {
        static std::ofstream logFile(ERROR_LOG_FILEPATH, std::ofstream::out | std::ofstream::trunc);
        logFile << message.getLogMessage();
        logFile.flush();
    }

So after the program shuts down, the log file contains all errors that happend during the last run. This works fine, unless no errors occurred. In the case of no error, the log file contains the errors of the run before the last one, as due to lazy initialization, the file was never opened (with the trunc option). Any way to force the static variable to be initialized?

Upvotes: 0

Views: 192

Answers (1)

Julien Lebot
Julien Lebot

Reputation: 3092

How about something like that:

class Log
{
    private:
       std::ofstream _logFile;
    public:
       Log()
       : _logFile(ERROR_LOG_FILEPATH, std::ofstream::out | std::ofstream::trunc)
       {
       }

       void writeErrorToLog(const LogMessage& message)
       {
           _logFile << message.getLogMessage();
           _logFile.flush();
       }
}

Then you can use a single instance of this class (apply singleton pattern). Whenever the class is instantiated it will truncate the file no matter if there are errors or not.

You could also make the _logFile member static:

class Log
{
    private:
       static std::ofstream _logFile;
    public:
       static void writeErrorToLog(const LogMessage& message)
       {
           _logFile << message.getLogMessage();
           _logFile.flush();
       }
}

// In cpp
std::ofstream Log::_logFile(ERROR_LOG_FILEPATH, std::ofstream::out | std::ofstream::trunc);

That way you can just access it like that:

Log::writeErrorToLog(...)

Upvotes: 1

Related Questions