如何建立和设置公司网站,做网站框架,成都网站建设成都网络公司,网络推广方案swot分析实现单例步骤: 1.构造函数私有化。 2.增加静态私有的当前类的指针变量。 3.提供静态对外接口#xff0c;可以让用户获得单例对象。
单例 分为#xff1a; 1.懒汉式 2.饿汉式
懒汉式 代码如下:
class Singleton_lazy
{
public:static Singleton_lazy *getInstance(){if (pS…实现单例步骤: 1.构造函数私有化。 2.增加静态私有的当前类的指针变量。 3.提供静态对外接口可以让用户获得单例对象。
单例 分为 1.懒汉式 2.饿汉式
懒汉式 代码如下:
class Singleton_lazy
{
public:static Singleton_lazy *getInstance(){if (pSingleton nullptr){pSingleton new Singleton_lazy;}return pSingleton;}private:Singleton_lazy() {}static Singleton_lazy * pSingleton;
};Singleton_lazy * Singleton_lazy::pSingleton nullptr;饿汉式 代码如下:
#include iostream
using namespace std;class Singleton_hungry
{public:
static Singleton_hungry *getInstance(){return pSingleton;}private:Singleton_hungry(){cout 我是饿汉式 endl;}static Singleton_hungry * pSingleton;
};Singleton_hungry * Singleton_hungry::pSingleton new Singleton_hungry;int main()
{cout main start endl;return 0;
}
测试结果:
测试是否为单例? 代码如下:
#include iostream
using namespace std;class Singleton_lazy
{
public:static Singleton_lazy *getInstance(){if (pSingleton nullptr){pSingleton new Singleton_lazy;}return pSingleton;}private:Singleton_lazy() {}static Singleton_lazy * pSingleton;
};Singleton_lazy * Singleton_lazy::pSingleton nullptr;class Singleton_hungry
{
public:static Singleton_hungry *getInstance(){return pSingleton;}
private:Singleton_hungry(){}static Singleton_hungry * pSingleton;
};Singleton_hungry * Singleton_hungry::pSingleton new Singleton_hungry;void test01()
{Singleton_lazy *p1 Singleton_lazy::getInstance();Singleton_lazy *p2 Singleton_lazy::getInstance();if (p1 p2){cout 两个指针指向同一块内存空间是单例 endl;}else{cout 不是单例 endl;}Singleton_hungry *p3 Singleton_hungry::getInstance();Singleton_hungry *p4 Singleton_hungry::getInstance();if (p3 p4){cout 两个指针指向同一块内存空间是单例 endl;}else{cout 不是单例 endl;}}int main()
{test01();return 0;
}测试结果:
单例对象释放问题: 不需要考虑内存释放只有一个对象占的内存太小不会造成内存泄漏。
单例碰到多线程: 懒汉式碰到多线程是线程不安全的。
饿汉式碰到多线程是线程安全的。