饿汉:一开始就实例化对象
懒汉:调用(需要)才去实例化对象
写法一,可用于懒汉和饿汉
线程安全
singleton.h
#ifndef SINGLETON_H
#define SINGLETON_H
#include <mutex>
#define DECLARESINGLETON(class_name) \
private: \
static class_name *_instance; \
public: \
static class_name *instance() \
{ \
static std::mutex mutex; \
if(!_instance) \
{ \
std::lock_guard<std::mutex> lock(mutex); \
if(!_instance) \
{ \
_instance = new class_name; \
} \
} \
return _instance; \
} \
private: \
class_name(){} \
#endif // SINGLETON_H
写法二 利用c++11
利用c++11静态局部变量,底层双检查机制实现线程安全。
mysingleton.h
#ifndef MYSINGLETON_H
#define MYSINGLETON_H
#endif // MYSINGLETON_H
#define MYDECLARESINGLETON(class_name) \
private: \
class_name(){} \
public: \
static class_name *instance() \
{ \
static class_name _instance;\
return &_instance; \
} \
写法三,无c++11
mysingleton.h
#ifndef SINGLETON_H
#define SINGLETON_H
#include <mutex>
#define DECLARESINGLETON(class_name) \
public: \
static class_name *instance() \
{ \
static class_name *_instance = nullptr \
static std::mutex mutex; \
if(!_instance) \
{ \
std::lock_guard<std::mutex> lock(mutex); \
if(!_instance) \
{ \
_instance = new class_name; \
} \
} \
return _instance; \
} \
private: \
class_name(){} \
#endif // SINGLETON_H
调用
test1.h
#ifndef TEST1_H
#define TEST1_H
#include "singleton.h"
class test1
{
DECLARESINGLETON(test1)
public:
int add(int,int);
};
#endif // TEST1_H
test1.cpp
#include "test1.h"
#include <iostream>
//test1* test1::_instance = nullptr; // 写法一使用时去掉注释,懒汉
//test1* test1::_instance = new test1; // 写法一使用时去掉注释,饿汉
int test1::add(int a,int b)
{
test1 *p = test1::instance();
std::cout << p << std::endl;
return a+b;
mian.cpp
#include <iostream>
#include "test1.h"
using namespace std;
int main()
{
test1 *p1 = test1::instance();
test1 *p2 = test1::instance();
cout << p1 << endl;
cout << p2 << endl;
return 0;
}