简体   繁体   English

C ++:如何摆脱惰性初始化

[英]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). 在没有错误的情况下,日志文件将包含最后一次运行之前的运行错误,因为由于延迟初始化,该文件从未打开(使用trunc选项)。 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: 您还可以将_logFile成员设为静态:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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