24小时热门版块排行榜    

Znn3bq.jpeg
查看: 146  |  回复: 1
当前主题已经存档。

zsglly

木虫 (著名写手)

[交流] C++实现单件的初探

在《设计模式》中有一个叫做单件(Sigleton)的模式,是用来控制创建唯一对象。书中只讲到了如何建立Singleton对象
,对于如何来销毁此对象则只字不提。但是对象生命的管理对于C++程序员来说是多么的重要呀。或许Singleton只
是属于创建模式的一种,大师们认为在这里不应涉及到“销毁模式”。

有人认为Sinleton是应该在程序的退出的时候销毁的。但是退出应该是在什么时候呢。
请看如下代码:
假设是按设计模式里的方式来写一个对象Singlton对象。


class Singlton
{
private:
    static Singlton * _insatnce;
    Singlton()
    {
        cout<<"object is ["<     }
public:
    ~Singlton()
    {
        cout<<"object is ["<"<         _insatnce = 0;
    }

    static Singlton * GetSinglton()
    {
        if(_insatnce)
            return _insatnce;
      
        _insatnce = new Singlton;
         
        return _insatnce;
    }
    void Dosomething()
    {
        cout<<"object is ["<     }
};

Singlton * Singlton::_insatnce = NULL;

void foo(int i)
{
    /*

        程序体
    */
    if(i)
        Singlton::GetSinglton()->Dosomething();
    /*

        程序体
    */
}
int main()
{
    /*
        void ;
        程序体
    */
    foo(1)

//  if(Singlton::_insatnce)   
//       Singlton::GetSinglton(); 不能编译
    delete Singlton::GetSinglton();
}

事实上如果在Singlton某次运行根本就没有调用过foo(1)而只是调用了foo(0),但是还必
须得在最后程序退出时调用实际上这时候调用GetSinglton()来建立对象马上就被删除了
。这是完全没有必要也是浪费的。想在程序执行时使用判断语句也是行不通的。这样的实
现还是可以改进的,使用在Singlton中再增加一个静态的成员函数CheckExistInstance来判
断对象是否存在,可以提高效率。但这样又给对象增加了接口,增加了代码维护的开销。

但是对象在程序结束时你并不清楚是不是真的不再需要此对象了。我们再修改代码如下。

class Singlton
{
private:
    static Singlton * _insatnce;
    Singlton()
    {
        cout<<"object is ["<     }
public:
    ~Singlton()
    {
        cout<<"object is ["<"<         _insatnce = 0;
    }

    static Singlton * GetSinglton()
    {
        if(_insatnce)
            return _insatnce;
      
        _insatnce = new Singlton;
         
        return _insatnce;
    }
    void Dosomething()
    {
        cout<<"object is ["<     }
};

Singlton * Singlton::_insatnce = NULL;

void foo(int i)
{
    /*

        程序体
    */
    if(i)
        Singlton::GetSinglton()->Dosomething();
    /*

        程序体
    */
}

class TestSingleton
{
public:
    TestSingleton()
    {
        Singlton::GetSinglton()->Dosomething();
    }
    ~TestSingleton()
    {
        Singlton::GetSinglton()->Dosomething();//此处出现内存泄露
    }
};
TestSingleton _test;
int main()
{
    /*
        void ;
        程序体
    */
    foo(1);

    delete Singlton::GetSinglton();
}

且看~TestSingleton()申请出来的对象应该由谁来释放呢。由此引发了有人主张使用
引用记数器由模仿COM的Release来实现.实现代码如下
class Singleton
{
private:
    static int m_Ref;
    static Singleton * _instance;
public:
    void DoSomething()
    {
        cout<<"object is ["<     }

    static Singleton * GetSinglton()
    {
        if(_instance)
        {
            ++m_Ref;
            return _instance;
        }
        _instance = new Singleton;
        ++m_Ref;
        return _instance;
    }
     
    ULONG Release()
    {
        --m_Ref;
        if(0 == m_Ref)
        {
            delete _instance;
            _instance = NULL;
            return 0;
        }
        return m_Ref;
    }
private:
    Singleton()
    {
        cout<<"object is ["<     }
    ~Singleton()
    {
        cout<<"object is ["<"<     }
};
Singleton *Singleton::_instance = NULL;
int Singleton::m_Ref = 0;


void foo()
{
    Singleton * p = Singleton::GetSinglton();
    p->DoSomething();
    p->Release();
}

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
    Singleton * p = Singleton::GetSinglton();
    p->DoSomething();
    p->Release();

    foo();
    return 0;
}

这样的方式是不存在内存泄露的,并且这段代码表面上是个单件;实际上,
Singleton对象是被多次建立和销毁的,如果这个对象不像以上代码写得那么简单,
是如果在单件中申请了不小的内存,那么以上的代码是多么的不可想象呀!更有如
果单件里记录了像使用次数那样的状态变量,那情况就更糟糕了。
事实上单件的实现并不比想像中的那样难。我们且看

class Singlton
{
private:
    Singlton()
    {
        cout<<"object is ["<     }
public:
    ~Singlton()
    {
        cout<<"object is ["<"<     }

    static Singlton & GetSinglton()
    {
        static Singlton s;
        return s;
    }
    void Dosomething()
    {
        cout<<"object is ["<     }
};

void foo(int i)
{
    /*

        程序体
    */
    if(i)
        Singlton::GetSinglton().Dosomething();
    /*

        程序体
    */
}
class TestSinglton
{
public:
    TestSinglton()
    {
    Singlton::GetSinglton().Dosomething();
    }
    ~TestSinglton()
    {
    Singlton::GetSinglton().Dosomething();
    }
};
TestSinglton test1;
int main()
{
    /*
        void ;
        程序体
    */
    TestSinglton test2;
    foo(1);
    return 0;
}

这里用到的一个技巧就是使用了静态的变量,很明显有如下的好处:

1)如果在此次运行时根本没有用到单件,对像是不会被建立的。
2)需要用户来关心对象的释放
3)完全符合设计要求

[ Last edited by 幻影无痕 on 2006-11-27 at 08:16 ]
回复此楼

» 猜你喜欢

做人要厚道啊!厚道啊!
已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖

zsglly

木虫 (著名写手)

送上2005年对各虫虫的最后祝福,HAPPY NEW YEAR!
做人要厚道啊!厚道啊!
2楼2005-12-31 22:29:50
已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖
相关版块跳转 我要订阅楼主 zsglly 的主题更新
普通表情 高级回复 (可上传附件)
最具人气热帖推荐 [查看全部] 作者 回/看 最后发表
[考研] 急需调剂 +7 绝不放弃22 2026-04-15 7/350 2026-04-16 22:09 by SUSE_CL
[考研] 0831生医工第一轮调剂失败求助 +14 小熊睿睿_s 2026-04-11 18/900 2026-04-16 20:41 by lpl364211
[考研] 26药学专硕105500求调剂 +6 喽哈加油 2026-04-13 7/350 2026-04-16 14:31 by zhouxiaoyu
[考研] 一志愿中科大材料与化工,353分还有调剂学校吗 +7 否极泰来2026 2026-04-15 9/450 2026-04-16 13:40 by liumingli7817
[考研] 289 分105500药学专硕求调剂(找B区学校) +4 白云123456789 2026-04-13 4/200 2026-04-16 00:18 by 粉沁若尘
[考研] 一志愿A区211,22408 321求调剂 +6 随心所欲☆ 2026-04-15 7/350 2026-04-15 21:45 by lbsjt
[考研] 通信工程求调剂!!! +6 zlb770521 2026-04-14 6/300 2026-04-15 20:00 by 学员JpLReM
[考研] 272分材料子求调剂 +41 Loy0361 2026-04-10 54/2700 2026-04-14 18:00 by lhj2009
[考研] 各位老师好,求调剂,本科211,一志愿天津大学生物与医药学硕,差两名录取。 +11 路六六jjj 2026-04-13 11/550 2026-04-14 16:01 by zs92450
[教师之家] 转长聘了 +7 简单化xn 2026-04-13 7/350 2026-04-14 14:50 by xindong
[考研] 考研调剂 +13 长弓傲 2026-04-13 14/700 2026-04-14 14:44 by zs92450
[考研] 农学0904 312求调剂 +4 Say Never 2026-04-11 4/200 2026-04-14 09:10 by zs92450
[考研] 材料085601调剂 +32 何润采123 2026-04-10 34/1700 2026-04-14 08:47 by 木木mumu~
[考研] 求调剂288 +7 ioodiiij 2026-04-10 9/450 2026-04-13 08:33 by Hayaay
[考研] 291求调剂 +8 关忆北. 2026-04-11 8/400 2026-04-12 09:32 by 逆水乘风
[考研] 一志愿厦大0856,306求调剂 +15 Bblinging 2026-04-11 15/750 2026-04-11 22:53 by 314126402
[考研] 求调剂 +3 胃痉挛累了 2026-04-11 5/250 2026-04-11 14:13 by luhong1990
[考研] 284求调剂 +12 archer.. 2026-04-10 13/650 2026-04-11 08:44 by zhq0425
[考研] 263能源动力专硕求调剂 +4 加大号饭盒袋 2026-04-10 4/200 2026-04-10 20:52 by gong120082
[考研] 青岛科技大学材料学院,环境学院调剂补录4月10日以前都可以 +3 1青科大。 2026-04-09 5/250 2026-04-10 09:58 by 翩翩一书生
信息提示
请填处理意见