getinstance函数linux,C++单例模式

/单例模式:

C1 getInstance 和m_instance必是static变量,

C2 m_instance必被明确的初始化。

C3 构造函数与拷贝构造函数,析构函数 全是private,可以只声明。

C4 需要有明确的Destory函数

C5 需要在线程安全。/

//Singleton.h

#include

#include

#include

#include

using namespace std;

class Singleton{

private:

~Singleton(){Destory();};

Singleton(){};

//copy-construct:

Singleton(Singleton& s);

string m_name;

int m_id; //A1

int m_score;

public:

int show_info_no_const(void)

{

cout <

return 0;

}

int show_info(void) const

{

cout <

return 0;

}

void set_name(char* new_name);

static Singleton* getInstance(); //C2

void Destory();

static Singleton* m_instance; //C1

static pthread_mutex_t m_mutex;

};

//Singleton.cpp

#include

#include

#include

#include

#include

#include "Singleton.h"

using namespace std;

/*

单例模式:

C1 getInstance 和m_instance必是static变量,

C2 m_instance必被明确的初始化。

C3 构造函数与拷贝构造函数,析构函数 全是private,可以只声明。

C4 需要有明确的Destory函数

C5 需要在线程安全。

*/

Singleton* Singleton::getInstance()

{

if(m_instance == NULL) //如果真的空的话,再会加锁,再去完成原子的操作。

{

pthread_mutex_lock(&m_mutex); //互斥锁

if(m_instance == NULL)

{

m_instance = new Singleton;

}

pthread_mutex_unlock(&m_mutex); //互斥锁

}

return m_instance;

}

void Singleton::Destory()

{

delete this;

}

void Singleton::set_name(char* new_name)

{

m_name=new_name;

//m_id=9;//A1 m_id是不可以再被修改的。

}

Singleton* Singleton::m_instance = NULL; //C1 C2

pthread_mutex_t Singleton::m_mutex = PTHREAD_MUTEX_INITIALIZER;

//main.cpp

#include

#include

#include

#include

#include "Singleton.h"

int main()

{

Singleton::getInstance()->set_name("abc");

Singleton::getInstance()->show_info();

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值