#include
#include
namespace sdk_mobile{
/*
///单例模式, 多线程安全
///< 1. 饿汉方式, 使用全局静态变量,在程序启动时完成构建工作,
///< 线程安全, 但会减慢启动速度,同时在没有使用是内存已经创建
// template
class Singleton_1{
public:
static Singleton_1& instance(){
return *instance_;
}
static void destoryInstance(){
if(instance_ != nullptr){
delete instance_;
}
}
private:
Singleton_1() = default;
Singleton_1(const Singleton_1& ) = delete;
Singleton_1& operator=(const Singleton_1&) = delete;
static Singleton_1* instance_;
};
Singleton_1* Singleton_1::instance_ = new Singleton_1();
///< 2.懒汉方式: 线程不安全 ----> Double-Checked Locking Pattern
///< a. instance_ = new Singleton_2(): 此句代码会执行三件事:1.申请一块内存, 2.调用构造函数, 3.将内存地址赋值给instance_
///< 见: a1, a2
///< b. 采用std::unique_ptr 解决释放问题
class Singleton_2{
public:
static Singleton_2& instance(){
if(instance_ == nullptr){ ///a1 : 多线程读, 可能在a2 的步骤没有执行完, 访问了, 读取了, 调用了, 出现问题了
std::lock_guard
if(instance_ == nullptr){ ///a2 : 持有线程写, 写分为三步, 可能是乱序,
instance_.reset(new Singleton_2);
}
}
return *instance_;
}
~Singleton_2() = default;
private:
Singleton_2() = default;
Singleton_2(const Singleton_2& ) = delete;
Singleton_2& operator=(const Singleton_2&) = delete;
static std::unique_ptr
static std::mutex mutex_;
};
std::unique_ptr
std::mutex Singleton_2::mutex_;
///< 3. 懒汉方式,采用静态变量实现
class Singleton_3{
public:
static Singleton_3& instance(){
static Singleton_3 instance_;
return instance_;
}
~Singleton_3() = default;
private:
Singleton_3() = default;
Singleton_3(const Singleton_3& ) = delete;
Singleton_3& operator=(const Singleton_3&) = delete;
};
*/
///< 4. 采用std::call_once ,线程安全
template
class Singleton{
public:
static T& instance(){
static std::once_flag s_flag;
std::call_once(s_flag, [&]{
instance_ = std::unique_ptr
});
return *instance_;
}
protected:
Singleton() = default;
~Singleton() = default;
private:
///< delete 直接将object file文件中的符号删除
Singleton(const T&) = delete;
Singleton& operator= (const T& ) = delete;
static std::unique_ptr
};
template
std::unique_ptr
}