C++的单例模式

本文探讨了C++中实现单例模式的方法,包括如何使用智能指针防止内存泄漏,以及如何通过类中类确保单例的唯一性和正确释放。通过代码示例展示了不同实现方式对程序运行结果的影响。
										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

可见。单例模式下需要进行的内存释模型。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值