实时阴影绘制技术研究

C++博客 首页 新随笔 联系 聚合 管理
  48 Posts :: 20 Stories :: 57 Comments :: 0 Trackbacks
from:http://www.pconline.com.cn/pcedu/empolder/gj/c/0407/421424.html

ANSI C++ 中的 Singleton 实现说难不难,说容易也不容易,很多人写 ANSI C++ 的 Singleton class 都有错误。这篇文章讨论怎样在 ANSI c++ 中写 Singleton class, 希望对大家有帮助。

  《设计模式》中把 Singleton 写成返回指针:



class Singleton{
public:
    static Singleton* Instance();
protected:
    Singleton();
private:
    static Singleton* _instance;
};

      相应的实现 cpp 文件是:


Singleton* Singleton::_instance;
Singleton* Singleton::Instance(){
    if( _instance == 0){
        _instance = new Singleton;
    };
    return _instance;
}

 

    将构造函数设计成 protected 的目的是防止在 class 外面 new ,有人可能会设计成 private ,如果考虑到有可能会继承这个类的话,还是将构造函数设计成 protected 比较好,还需要加一个 virtual 析构函数。为了防止别人复制 Singleton 对象:


Singleton* pSingleton = Singleton::Instance();
Singleton s1 = *pSingleton;
Singleton s2 = *pSingleton;
需要将拷贝构造(copy constructor)函数变成 private。


    但是这里存在的问题是,什么时候删除 Singleton 对象?按照 C++ 的一个基本原则,对象在哪里创建就在哪里销毁,这里还应该放一个 destroy 方法来删除 Singleton 对象。如果忘了删除就比较麻烦。Instance 函数还存在多线程同时访问的加锁问题。如果把 Instance 函数开始和结尾放上加锁和解锁,整个函数性能会下降很多。这不是一个好的设计。
    有一个小小的改动,可以避免忘了删除 Singleton 对象带来内存泄露的问题。那就是用 std:auto_ptr 来包含 Singleton 对象,定义一个class static member auto_ptr 对象,在析构的静态 auto_ptr 变量的时候时候自动删除 Singleton 对象。为了不让用户 delete Singleton 对象,需要将析构函数由 public 变成 protected。以下是头文件 SingletonAutoPtr.h :


#include <memory>
using namespace std;
class CSingletonAutoPtr
{
private:
    static auto_ptr<CSingletonAutoPtr> m_auto_ptr;

posted on 2006-03-27 13:57 苦行僧 阅读(1121) 评论(2)  编辑 收藏 引用 所属分类: 转载

Feedback

# re: C++ 中的Singleton 类的实现讨论 2006-04-21 09:11 Stone Jiang
当一个单体类引用另一个单体类的时候,在析构时,还要多加小心.
  回复  更多评论
  

# re: C++ 中的Singleton 类的实现讨论 2006-04-22 05:56 苦行僧
但是我理解singlton一般就像static变量一样,很少作为一个对象的属性,实现上singlton也是用static来实现的,应该都是最后退出程序的时候析构吧。  回复  更多评论
  


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理