如何正确的在C++中实现单例SingleTone模式

博客介绍了单例模式,它能保证类始终只有一个实例对象,用于表现唯一资源且不可拷贝。实现时需注意两点,一是提供获取实例的接口,实例在类内部作为static成员,首次调用时构造;二是禁止用户构造和析构对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class S
{
    public:
        static S& getInstance()
        {
            static S    instance; // Guaranteed to be destroyed.
                                  // Instantiated on first use.
            return instance;
        }
    private:
        S() {}                    // Constructor? (the {} brackets) are needed here.

        // C++ 03
        // ========
        // Don't forget to declare these two. You want to make sure they
        // are inaccessible(especially from outside), otherwise, you may accidentally get copies of
        // your singleton appearing.
        S(S const&);              // Don't Implement
        void operator=(S const&); // Don't implement

        // C++ 11
        // =======
        // We can use the better technique of deleting the methods
        // we don't want.
    public:
        S(S const&)               = delete;
        void operator=(S const&)  = delete;

        // Note: Scott Meyers mentions in his Effective Modern
        //       C++ book, that deleted functions should generally
        //       be public as it results in better error messages
        //       due to the compilers behavior to check accessibility
        //       before deleted status
};

单例模式保证该类始终只有一个实例对象,以表现唯一资源的设计(不可拷贝)。
需要注意2点:

  1. 提供GetInstance接口用于获取实例,实例在类内部作为static成员存在,在首次调用GetInstance构造对象;
  2. 禁止用户构造和析构对象;

参考:How do you implement the Singleton design pattern?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值