单例模式(C++)以及共享问题

mac2024-03-21  27

//单例模式 class Single { private: Single(){}//构造函数私有 public: static Single * GetInstance()//使用静态函数创建对象 { if (my_instance == nullptr) { my_instance = new Single(); static DeleteObj d1; } return my_instance; } //使用内部类释放对象 class DeleteObj { public: ~DeleteObj() { if (Single::my_instance) { delete Single::my_instance; Single::my_instance = nullptr; cout << "析构" << endl; } } }; //其他正常函数 void func() { cout << "this is a public func" << endl; } private: static Single *my_instance; }; Single* Single::my_instance = NULL; int main() { Single* p_a = Single::GetInstance();//创建单例对象 Single* p_b = Single::GetInstance(); if (p_a == p_b) cout << "this is a identical obj" << endl; return 0; }

std::call_once使用

std::call_once(),C++11引入的函数,该函数第二个参数是一个函数名 call_once()保证函数只被调用一次,具备互斥量能力,比互斥量更高效 与一个标记结合使用: std::once_flag

static void CreateInstance()//用于std::call_once调用 { my_instance = new Single(); static DeleteObj d1; } static Single * GetInstance()//单例模式内部使用静态函数创建对象 { std::call_once(flag,CreateInstance); return my_instance; }
最新回复(0)