一个简单的例子:
#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"