单例模式

懒汉式:需要时才构造该单例
class CRemoteControl
{
public:
    ~CRemoteControl(void){ }

    static CRemoteControl& GetInstance()
    {
        if(m_rc == NULL)
            m_rc = new CRemoteControl();
        return m_rc;
    }
private:
    CRemoteControl(void)
    {
        cout << "CRemoteControl构造函数" << endl;
    }
private:
    static CRemoteControl* m_rc;
};
CRemoteControl* CRemoteControl::m_rc = NULL;


饿汉式:
class CRemoteControl
{
public:
    ~CRemoteControl(void){ }

    static CRemoteControl& GetInstance()
    {        
        return m_rc;
    }
private:
    CRemoteControl(void)
    {
        cout << "CRemoteControl构造函数" << endl;
    }
private:
    static CRemoteControl* m_rc;
};
//静态成员变量与全局变量一样,在编译期间分配内存,即在声明类对象之前创建,即在函数运行之前分配内存
CRemoteControl* CRemoteControl::m_rc = new CRemoteControl();

课题组使用的饿汉式:没有使用指针,而是使用了static局部变量
class CRemoteControl
{
public:
    ~CRemoteControl(void){ }

    //返回引用和返回对象的原则:不能返回局部对象的引用;其余均可以也应该返回引用。
    static CRemoteControl& GetInstance()
    {
        //对局部变量用static声明,把它分配在静态存储区,变量在整个程序执行期间不释放,其所分配的空间始终存在
        //对全局变量用static声明,则该变量的作用域只限于本文件模块
        static CRemoteControl remoteControl; 
        cout << &remoteControl << endl;//始终是同一个变量
        return remoteControl;
    }
private:
    CRemoteControl(void)
    {
        cout << "CRemoteControl构造函数" << endl;
    }
private:
};
#define g_remoteControl CRemoteControl::GetInstance()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值