std::ofstream 不会写入文件(有时)

std::ofstream won't write to file (sometimes)

我已经审阅过许多标题相同或相似的问题,我更改代码的方式太多了,我什至数不清....我有一个有趣的问题。
我有一个 class 用于日志记录,它非常简单,只需将内容写入文件即可。完全相同的代码在构造函数中有效,但在成员函数中无效。我去掉了一些不相关的代码,剩下的是:

private:
    std::string logfile_path_;
    std::string program_name_;
    std::string GetTimestamp() {
        timeval tv;
        gettimeofday(&tv, NULL);
        char cTimestamp[24];
        strftime(cTimestamp, sizeof(cTimestamp), "%F %T", std::localtime(&tv.tv_sec));
        sprintf(&cTimestamp[19], ".%03d", (tv.tv_usec / 1000));         // write the miliseconds (microseconds/1000) into cTimestamp starting at the 20th character. %03d == pad with 0, for a minimum length of 3, an integer.
        return cTimestamp;      // function returns std::string so this will be implicitly cast into a string and returned.
    }

public:
    int log_level_;

    SrxDsLog(std::string Logfile_path, std::string program_name, int log_level) {
        log_level_ = log_level;
        program_name_ = program_name;
        logfile_path_ = Logfile_path;
        std::ofstream logfile(logfile_path_.c_str(), std::ios::out | std::ios::app);
        std::cout << "Logger started, Log file: " << logfile_path_ << std::endl;
        logfile << "Logger started, Log file: " << logfile_path_ << std::endl;
        return;
    }

    void WriteLog(std::string Log_message, int Severity = LOG_CRITICAL, std::string Function_name = "") {
        if (Severity >= log_level_) {
            std::cout << GetTimestamp() << "|" << program_name_ << "|" << Function_name << "|" << GetSeverity(Severity) << "|" << Log_message << std::endl;
            std::ofstream logfile(logfile_path_.c_str(), std::ios::out | std::ios::app);
            logfile << GetTimestamp() << "|" << program_name_ << "|" << Function_name << "|" << GetSeverity(Severity) << "|" << Log_message << std::endl;
        }
    }

问题是为什么它在构造函数中工作,但完全相同的代码在成员函数中不起作用。 std::cout 正在写入我想要的完全相同的日志消息,但它没有出现在文件中。每次程序 运行.

时,文件都包含一行
int log_level_;

构造函数无法初始化此 class 成员。

随后,与此 class 成员的比较导致未定义的行为。

在令人惊讶的令人不满意的事件中,我投票结束了我的问题。
该问题显然是由无关代码中的未定义行为引起的。那是因为我做了一些在 C++11 中定义但在 C++03 中没有定义的事情。显然你不能从 C++03 中的构造函数中调用构造函数....
正因为如此,并且因为这个问题没有包括实际出错的代码,这个问题看起来非常糟糕。

请关闭。