单例模式式

单例模式式,第1张

有的时候需要一个类只能被实例化一次,就是这个单例模式,说是设计模式,但是这个方法主要的难度在语言上,怎么利用static实现单例。



特点就是把构造变成私有的,这样类外就不能定义了,但是却可以通过static函数在类内构造自己。


构造后生成的static指针可以在类内维护,如果有人妄图再实例化一个类,就自然能够制止了。



下面通过调用static函数将自己实例化,再调用自己,如果有人再调用自己返回的还是之前的指针。


多线程的时候不同的线程同时getinstance()是可能生成多个实例的,因此加锁。


#include
#include
class singleton
{
    public:
        static singleton* getInstance(void)
        {
            if(nullptr == singleton::instance)
            {
                std::lock_guardlocker(g_lock);///<多线程同时单例模式时会异常
                singleton::instance = new singleton;
            }
            return instance;
        }
        static void destroyInstance(void)
        {
            if(nullptr != instance)
            {
                delete(instance);
                instance = nullptr;
            }
            return;
        }
        static void print(void)
        {
            std::cout<<"what???????"<print();
    auto p1 = singleton::getInstance();

    if(p==p1)
        std::cout<<"same"<

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/578590.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-04-11
下一篇2022-04-11

发表评论

登录后才能评论

评论列表(0条)