C++的单例模式

单例模式,只实例化出一个对象(全局静态变量,各个域都可以调用)。

为了只实例化出一个对象,会将默认构造函数私有,将拷贝构造函删除,由于实例出是的同一个对象,当这个对象被多个线程使用(线程安全问题)或多个模板类使用(重复调用析构函数),需要将析构函数私有,并需要锁进行安全保护,我们需要在public下写能够调用默认构造函数(只调用一次)和析构函数的两个自定义函数。

分为懒汉模式和饿汉模式

1.懒汉模式

class singleton
{
public:
	static singleton* Getobj()
	{
		// 要防止抛异常
		if(slt == nullptr)//  只有第一次需要加锁   双检查
		{
			unique_lock<mutex> ul(_mtx);	 //  出了if(){} 域自动销毁
			if (slt == nullptr)
			{
				slt = new singleton;     //  new出来(在堆上)的而非默认构造函数实例化的对象,必须手动释放空间
			//	std::atexit(destoryInstance); //  注册销毁函数,一个回调函数,在程序正常退出时,自动执行,在main()函数结束后调用,可行,但更推荐智能指针和Meyers Singleton
			}
		}    //  花括号确定 域
		return slt;

	}

	static void destoryInstance()   // 调用析构函数
	{
		if (slt)   //  如果没有if,在多个线程的情况下,可能重复释放
		{
			cout << "destoryInstance():" << endl;
			delete slt;
			slt = nullptr;      //......必须置空,禁止重复释放
		}
	}

    singleton(const singleton& slt) = delete;
private:
	singleton() {};
	~singleton() { cout << "~singleton()" << endl; };    //   必须为私有,防止外部直接调用析构函数, delete单例对象   
	// 因为单例对象是全局或静态的,外部代码或不同模板多重调用delete(会调用析构函数)导致,导致重复释放内存,只需要保证最后一次用完后释放就行
	static singleton* slt;
	static mutex _mtx;    //  静态在类里面都是声明
};

singleton* singleton::slt = nullptr;   // 懒汉模式
mutex singleton::_mtx;

destoryInstance()函数不能替换成析构函数。

public:	
~singleton()      // 死循环
	{
		if (slt)
		{
            unique_lock<mutex> ul(_mtx);
			cout << "~singleton():" << endl;
			delete slt;
			slt = nullptr;
		}
	}

1.会被其他线程或模板类调用析构函数,导致重复释放(有了if和锁似乎不会发生)。

2.更重要的原因:单例模式的对象是自引用,就是我包含我自己,我自己就是我的成员,发生delete时,如果成员有自定义类型,要调用成员的析构函数,而单例对象的成员就是自己,导致无线死循环。

new 出的空间需要我们手动释放,可以通过智能指针自动释放。

class GC
{
public:
	~GC()
	{
		singleton::destoryInstance();
	}
};
static GC gc;    //    当gc生命周期结束,优先调用类中的析构函数  //  非单例在栈上创建后自动析构(析构函数为public)

或者直接调用内置智能指针shared_ptr。

饿汉模式

就是说不管你将来用不用,程序启动时就创建一个唯一的实例对象。

优点:简单

缺点:可能会导致进程启动慢,且如果有多个单例类对象实例启动顺序不确定。 如果这个单例对象在多线程高并发环境下频繁使用,性能要求较高,那么显然使用懒汉模式来避免资源竞争,提高响应速度更好。

C++的四种类型转化语法

static_cast ,reinterpret_cast,const_cast,dynamic_cast

test
{
    	// C中的模式
	int i = 0;
	double d = 8.8;
	i = d;
	cout << i << endl;   // C中的支持近似的隐式类型转化


	int* p = nullptr;
	p = (int*)i;
	cout << p << endl;  //C中支持强转类型转化

}

static_cast对于近似类型的转化,reinterpret_cast强制转化,用于不近似类型之间的转化。

test
{
    //......
    i = static_cast<int>(d);   //  static_cast 支持近似的类型转化
	cout << i << endl;

	p = reinterpret_cast<int*>(i);  //  reinterpret_cast支持强转类型转化(不近似类型)
	cout << p << endl;  
}

const_cast

修改最初定义为非 const 的对象: 当对象本身不是 const,但通过 const 指针/引用访问,可以用const_cast去除指针/引用的const。

	int a = 1;   
	const int* pa = &a;
	*const_cast<int*>(pa) = 20;
	const int* paa = &a;  //与之对应

	cout << "a:" << a << "  " << "*pa:" << *pa << "  " << "*paa:" << *paa << endl;
	*const_cast<int*>(paa) = 30;
	cout << "a:" << a << "  " << "*pa:" << *pa << "  " << "*paa:" << *paa << endl;
结果:
a:20  *pa:20  *paa:20
a:30  *pa:30  *paa:30

 使用 const_cast 移除 const 后修改真正的 const 对象会导致未定义行为,虽然可以正常运行,没允许,没禁止,属于未定义的行为。

	const int x = 42;
	cout << "x:" << x << endl;

	const int* p3 = &x;
	*const_cast<int*>(p3) = 20;   //  未定义行为
	cout << "x:" << x << "  " << "p3:" << *p3 << endl;

	int* p2 = const_cast<int*>(&x);       
	*p2 = 100;                 //未定义行为
	cout << "x:" << x << "  " << "p3:" <<*p3 <<"  " << "p2:" << *p2 << endl;
    cout <<"&x:"<< & x << "  " << p2 << "  " << p3 << endl;


结果:
x:42
x:42  p3:20
x:42  p3:100  p2:100
&x:0075FAC8  0075FAC8  0075FAC8

可以看出 p2和p3是相互影响的,而x没变,但他们的地址一样。由于x被放入了寄存器,这里从寄存器中取,不变,本质是编译器对const对象存取优化机制导致的,想要每次取内存中取x就加  volatile。

	volatile const int x = 42;
	cout << "x:" << x << endl;

	//const int* p3 = &x;
	//*const_cast<int*>(p3) = 20;
	int* p3 = const_cast<int*>(&x);
	*p3 = 20;
	cout << "x:" << x << "  " << "p3:" << *p3 << endl;

	int* p2 = const_cast<int*>(&x);       
	*p2 = 100; 
	cout << "x:" << x << "  " << "p3:" <<*p3 <<"  " << "p2:" << *p2 << endl;

	cout <<"&x:"<< & x << "  " << p2 << "  " << p3 << endl;

结果:
x:20  p3:20
x:100  p3:100  p2:100
&x:1  007DFC50  007DFC50

加了volatile之后x的值直接从内存中拿取,但由于未定义行为,导致x的地址错误,所以使用未定义行为危害很大。

dynamic_cast

用于检测在继承关系中,转化为子类指针(引用)的是父类还是子类。

class A
{
public:
	virtual void fun() {};
private:
	int _c;
	int _d;
};

class B :public A
{
public:
	int _a;
	int _b;
private:
};
void func(A* a)
{
	//如何区分a是父类对象还是子类对象
	//B* b = (B*)a;
	B* b = dynamic_cast<B*>(a); //  如果a指向子类,则转化成功  //如果pa指向父类,则转化失败返回nullptr;
	if (b)
	{
		cout << "转化成功:a指向子类对象" << endl;
		b->_a = 1;
		b->_b = 2;
	}
	else
	{
		cout << "转化失败:a指向父类对象" << endl;
	}
}
void test7()
{
	A a;
	B b;
	func(&a);
	func(&b);
}


结果:
转化失败:a指向父类对象
转化成功:a指向子类对象

explicit禁止隐式类型的转化

class AB
{
public:
	 explicit AB(const int&&a,const int&& b)
		:_a(a)
		,_b(b)
	 {
		 cout << "AB()" << endl;
	 }

	 //AB(initializer_list<int> p)
	 //{
		// cout << "AB()" << endl;
	 //}


	void func1(int a)
	{
		cout << "int a" << endl;
	}

	void func2(int a,int b)
	{
		cout << "int a , int b" << endl;
	}

private:
	int _a;
	int _b;
};


void test8()
{
	AB a(1, 2);
	AB b = { 1,2 };   //  此处发生了隐式类型的转化,加explicit 报错   //  std::initializer_list<int>
}

如果加上以下函数就不会报错了

	 AB(initializer_list<int> p)
	 {
		 cout << "AB()" << endl;
	 }


 

### 单例模式的基本概念 单例模式是创建型设计模式的一种,其核心思想是确保一个类仅有一个实例,并提供一个全局访问点来获取这个实例。在程序运行期间,单例模式可以保证一个类只有一个实例对象,并提供全局访问接口[^1][^2][^4]。 ### 实现方法 #### 饿汉式 饿汉式在程序开始时就创建实例,线程安全,但可能会造成资源浪费。 ```cpp #include <iostream> class Singleton { public: static Singleton& getInstance() { return instance; } void showMessage() { std::cout << "Hello from Singleton!" << std::endl; } private: Singleton() { std::cout << "Singleton Constructor Called" << std::endl; } // 防止复制 Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; static Singleton instance; }; Singleton Singleton::instance; int main() { Singleton& instance1 = Singleton::getInstance(); Singleton& instance2 = Singleton::getInstance(); instance1.showMessage(); if (&instance1 == &instance2) { std::cout << "Both instances are the same." << std::endl; } return 0; } ``` #### 懒汉式(非线程安全) 懒汉式在第一次使用时才创建实例,但非线程安全。 ```cpp #include <iostream> class Singleton { public: static Singleton* getInstance() { if (instance == nullptr) { instance = new Singleton(); } return instance; } void showMessage() { std::cout << "Hello from Singleton!" << std::endl; } private: Singleton() { std::cout << "Singleton Constructor Called" << std::endl; } // 防止复制 Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; static Singleton* instance; }; Singleton* Singleton::instance = nullptr; int main() { Singleton* instance1 = Singleton::getInstance(); Singleton* instance2 = Singleton::getInstance(); instance1->showMessage(); if (instance1 == instance2) { std::cout << "Both instances are the same." << std::endl; } return 0; } ``` #### 懒汉式(线程安全) 使用互斥锁保证线程安全,但会有一定的性能开销。 ```cpp #include <iostream> #include <mutex> class Singleton { public: static Singleton& getInstance() { std::lock_guard<std::mutex> lock(mutex); if (instance == nullptr) { instance = new Singleton(); } return *instance; } void showMessage() { std::cout << "Hello from Singleton!" << std::endl; } private: Singleton() { std::cout << "Singleton Constructor Called" << std::endl; } // 防止复制 Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; static Singleton* instance; static std::mutex mutex; }; Singleton* Singleton::instance = nullptr; std::mutex Singleton::mutex; int main() { Singleton& instance1 = Singleton::getInstance(); Singleton& instance2 = Singleton::getInstance(); instance1.showMessage(); if (&instance1 == &instance2) { std::cout << "Both instances are the same." << std::endl; } return 0; } ``` #### 基于局部静态变量(C++11及以上) 简洁、安全且高效,推荐使用。 ```cpp #include <iostream> class Singleton { public: static Singleton& getInstance() { static Singleton instance; return instance; } void showMessage() { std::cout << "Hello from Singleton!" << std::endl; } // 防止复制 Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; private: Singleton() { std::cout << "Singleton Constructor Called" << std::endl; } }; int main() { Singleton& instance1 = Singleton::getInstance(); Singleton& instance2 = Singleton::getInstance(); instance1.showMessage(); if (&instance1 == &instance2) { std::cout << "Both instances are the same." << std::endl; } return 0; } ``` ### 使用场景 - **资源管理**:例如数据库连接池、文件系统操作等,避免多个实例同时操作同一资源导致冲突。 - **配置信息**:如全局的配置文件管理,确保所有模块使用相同的配置信息。 - **日志记录**:保证所有日志信息都记录到同一个日志文件中。 ### 注意事项 - **线程安全**:在多线程环境下,需要确保单例的创建和访问是线程安全的,可采用互斥锁或局部静态变量的方式。 - **生命周期管理**:确保单例对象在整个程序生命周期内的正确性,避免内存泄漏。 - **可测试性**:单例模式可能会影响代码的可测试性,可考虑使用依赖注入等技术来提高可测试性。 - **避免滥用**:单例模式会引入全局状态,过度使用可能导致代码耦合度增加,难以维护和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值