C++的单例模式
/*
* C++的单例模式
*/
#include <iostream>
//定义类A--只包含一个实例对象
class A
{
private:
A(){}
A(const A &p){}
static A* instance;
public:
static A* getInstance()
{
if(instance == NULL)
{
instance = new A();
}
return instance;
}
void show()
{
std::cout << "show" << std::endl;
}
};
A* A::instance = NULL;
int main() {
/*调用函数*/
A::getInstance()->show();
return 0;
}
在以上的代码中保证了在程序的执行过程中只有一个对象实例的存在,但是有一个问题,instance这个指针没有被释放,为了解决这个问题,可以使用智能指针。如下:
/*
* C++的单例模式
*/
#include <iostream>
//定义类A--只包含一个实例对象
#include <memory>
class A
{
private:
A(const A &p){}
static std::shared_ptr<A> instance;
public:
A(){}
static std::shared_ptr<A> getInstance()
{
if(instance == NULL)
{
instance = std::make_shared<A>();
}
return instance;
}
void show()
{
std::cout << "show" << std::endl;
}
};
std::shared_ptr<A> A::instance = NULL;
int main() {
/*调用函数*/
A::getInstance()->show();
return 0;
}
但是这里又出现了问题,在使用此种指针的时候需要把构造函数放在public修饰的情况下,所以在main函数中可以实例化多个对象,这与我们设计初衷不符合。为此引入一个类中类来进行instance指针的释放,在保证只有一个对象时的内存不至于泄露。代码如下:
/*
* C++的单例模式
*/
#include <iostream>
//定义类A--只包含一个实例对象
class A
{
private:
A(){}
A(const A &p){}
~A(){
std::cout << "析构函数被调用" << std::endl;
}
static A* instance;
public:
static A* getInstance()
{
if(instance == NULL)
{
instance = new A();
}
return instance;
}
void show()
{
std::cout << "show" << std::endl;
}
class Test
{
public:
~Test()
{
if(instance != NULL)
{
delete instance;
instance = NULL;
}
}
};
static Test test;
};
A* A::instance = NULL;
A::Test A::test;
int main() {
/*调用函数*/
A::getInstance()->show();
return 0;
}
程序运行结果为:
show
析构函数被调用
将下面部分代码注释后为:
// if(instance != NULL)
// {
// delete instance;
// instance = NULL;
// }
程序运行结果为:
show
可见。单例模式下需要进行的内存释模型。
本文探讨了C++中实现单例模式的方法,包括如何使用智能指针防止内存泄漏,以及如何通过类中类确保单例的唯一性和正确释放。通过代码示例展示了不同实现方式对程序运行结果的影响。

873

被折叠的 条评论
为什么被折叠?



