简体   繁体   中英

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?

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(...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM