C++ static 變量的釋放時間及文件寫入引發的亂序,覆蓋問題

一個簡單的例子:

#include <iostream>
#include <stdlib.h>
#include <fstream>

using namespace std;
class Log{
private:
    int m_id;
    std::fstream m_f;
public:
    Log(int id, const std::string& filename) :m_id(id){
        cout << "created: " << id << endl;
        m_f.open(filename,std::fstream::out);
    }
    ~Log(){
        cout << "bye: " << m_id << endl;
        m_f.close();
    }
    void log(const string& info){
        cout << info << endl;
        m_f << info;
    }

};
void test(){
    static  Log log(1,"log.log");
    log.log("hello ");
}
void test2(){
    static Log log(2,"log.log");
    log.log("world");
}
int main(){
    {
        test();
        test2();
        cout << "bye main thread" << endl;
    }
    cout << "bye end" << endl;
}

結果

created: 1
hello 
created: 2
world
bye main thread
bye end
bye: 2
bye: 1

從結果中可以看出:

  • static變量log的釋放時間問進程結束時,並且按照變量創建時間由晚到早進行釋放。
  • 查看log.log 文件,發現內容爲"hello ",是因爲雖然兩個log都打開的相同的文件,m_f.open(filename,std::fstream::out) 返回的是相同的寫入位置,寫入會覆蓋掉。並且由於文件寫入是在緩衝區,並沒有寫入磁盤中。在程序結束清理堆棧時,將緩衝區的內容寫入。由於test2()內的log先釋放,導致”world“先寫入磁盤,然後"hello "。
  • 如果寫入時調用m_f.flush();結果爲world;
  • 如果將 log變量寫到函數外面,才能生成"hello world"
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章