#include <iostream>
|
#include <mutex>
|
#include <fstream>
|
#include <string>
|
#include <ctime>
|
using namespace std;
|
class A {
|
private:
|
ofstream logFile;
|
A() {
|
logFile.open("123.txt", ios::app);
|
}
|
~A() {
|
logFile.close();
|
}
|
A(const A &t){}
|
A& operator=(const A &t){}
|
static A* volatile s_obj;
|
static mutex g_mutex;
|
public:
|
static A* getInstance() {
|
if (s_obj == nullptr) {
|
lock_guard<mutex> guard(g_mutex);
|
if (s_obj == nullptr) {
|
s_obj = new A;
|
}
|
}
|
return s_obj;
|
}
|
void write(const string& level, const string& description, const string& time) {
|
logFile << "[" << level << "] " << "[" << time << "] " << description << endl;
|
}
|
void release() {
|
if (s_obj) {
|
delete s_obj;
|
s_obj = nullptr;
|
}
|
}
|
};
|
|
A* volatile A::s_obj = nullptr;
|
mutex A::g_mutex;
|
|
int main() {
|
A* a1 = A::getInstance();
|
A* a2 = A::getInstance();
|
if (a1 == a2) {
|
cout << "单例成功" << endl;
|
}
|
else {
|
cout << "单例失败" << endl;
|
}
|
time_t now = time(nullptr);
|
char buffer[80];
|
struct tm timeinfo;
|
localtime_s(&timeinfo, &now);
|
strftime(buffer, 80, "%Y - %m - %d %H:%M:%S", &timeinfo);
|
string timeStr(buffer);
|
a1->write("1", "日志", timeStr);
|
a1->release();
|
return 0;
|
}
|