Chinaunix首页 | 论坛 | 博客

分类: C/C++

2011-10-05 18:45:55

C++实现的委托机制(一)

 

作者:gouki04(啊古)  撰写日期:2011-09-27

博客链接:http://blog.csdn.net/gouki04

 

1.引言

       下面的委托实现使用的MyGUI里面的委托实现,MyGUI是一款强大的GUI库,想理解更多的MyGUI信息,猛击这里 最终的代码可以在这里下载: 我们的目标是要实现一个跟.NET几乎完全一样的委托,使用简单,支持多播,可以添加删除委托。同时支持C++的普通函数、模板函数、类成员函数,类的静态成员函数,并且支持多态。使用方式如下:

点击(此处)折叠或打开

  1. // 普通函数
  2. void normalFunc(){ cout << "func1" << endl; }

  3. class Base
  4. {
  5. public:
  6.     // 类成员函数
  7.     void classFunc(){ cout << "Base func1" << endl; }
  8. };

  9. int main()
  10. {
  11.     Base b;
  12.     CMultiDelegate myDelegate;
  13.     myDelegate += newDelegate(normalFunc);
  14.     myDelegate += newDelegate(&b, &Base::classFunc);
  15.     myDelegate(); // 此时会调用normalFunc和classFunc
  16.     
  17.     myDelegate -= newDelegate(&b, &Base::classFunc);
  18.     myDelegate(); // 此时会调用normalFunc

  19.     return 0;
  20. }

2.实现无参函数委托

       要实现委托,首先要解决的是封装C++中的函数指针。因为在C++中,普通函数指针和类成员函数指针是完全不一样的。如下例子:

点击(此处)折叠或打开

  1. class CMyClass
  2. {
  3. public:
  4.     void func(int);
  5. };

    定义一个指向CMyClass类型,参数列表为(int),返回值为void的函数指针typedef void (CMyClass::*ClassMethod) (int); // 注意定义时使用了特殊的运算符::*。那么此函数指针只能指向CMyClass类型的成员函数,不能指向其他类或者普通函数。类成员函数指针不能直接调用,要通过一个类实例来调用,如下: 

点击(此处)折叠或打开

  1. CMyClass *object = new CMyClass;
  2. ClassMethod method = CMyClass::func;
  3. (object->*method)(5); // 注意调用时使用了特殊运算符->*

    那么如何封装呢?我们先来定义下接口吧。(为了简单起见,下面的实现都是以无参函数为例,后续会讲到如何支持任意参数)

点击(此处)折叠或打开

  1. class IDelegate
  2. {
  3. public:
  4.     virtual ~IDelegate() { }
  5.     virtual bool isType(const std::type_info& _type) = 0;
  6.     virtual void invoke() = 0;
  7.     virtual bool compare(IDelegate *_delegate) const = 0;
  8. };

    IDelegate类的接口很少,也很简单,必要接口只有一个,就是invoke,用于触发函数,但为了可以方便管理,使用了isTypecompare函数来进行相等判断。下面是封装的普通函数指针: 

点击(此处)折叠或打开

  1. class CStaticDelegate : public IDelegate
  2. {
  3. public:
  4.     typedef void (*Func)();

  5.     CStaticDelegate(Func _func) : mFunc(_func) { }

  6.     virtual bool isType(const std::type_info& _type) { return typeid(CStaticDelegate) == _type; }

  7.     virtual void invoke() { mFunc(); }

  8.     virtual bool compare(IDelegate *_delegate) const
  9.     {
  10.         if (0 == _delegate || !_delegate->isType(typeid(CStaticDelegate)) ) return false;
  11.         CStaticDelegate * cast = static_cast<CStaticDelegate*>(_delegate);
  12.         return cast->mFunc == mFunc;
  13.     }

  14. private:
  15.     Func mFunc;
  16. };

    可以看到,CStaticDelegate只是简单地封装了普通函数指针,代码也非常简单,(类的某些成员函数,如isTypecompare使用了RTTI,对C++的动态类型判断不熟的可以猛击这里http://blog.csdn.net/gouki04/article/details/6796173)好了,注意了,下面开始封装类成员函数指针: 

点击(此处)折叠或打开

  1. template<class T>
  2. class CMethodDelegate : public IDelegate
  3. {
  4. public:
  5.     typedef void (T::*Method)();

  6.     CMethodDelegate(T * _object, Method _method) : mObject(_object), mMethod(_method) { }

  7.     virtual bool isType( const std::type_info& _type) { return typeid(CMethodDelegate) == _type; }

  8.     virtual void invoke()
  9.     {
  10.         (mObject->*mMethod)();
  11.     }

  12.     virtual bool compare(IDelegate *_delegate) const
  13.     {
  14.         if (0 == _delegate || !_delegate->isType(typeid(CMethodDelegate)) ) return false;
  15.         CMethodDelegate* cast = static_cast<CMethodDelegate* >(_delegate);
  16.         return cast->mObject == mObject && cast->mMethod == mMethod;
  17.     }

  18. private:
  19.     T * mObject;
  20.     Method mMethod;
  21. };

    首先解释一下:因为类成员函数指针与类的类型有关,不同类的成员函数指针是不一样的。要解决类型不同,很简单,使用模板就行。代码跟CStaticDelegate基本一样,下面稍微解释一下:CMethodDelegate类主要封装了一个类实例指针以及类成员函数的指针,这样在invoke时就不要额外的通过一个类实例了。要注意一点,compare函数的实现中,相等判定是类实例以及类函数指针都一样。也就是说就算是指针同一个成员函数,但实例不同,委托就不同。为了方便使用,定义函数newDelegate来创建委托使用的函数: 

点击(此处)折叠或打开

  1. inline IDelegate* newDelegate( void (*_func)() )
  2. {
  3.     return new CStaticDelegate(_func);
  4. }

  5. template<class T>
  6. inline IDelegate* newDelegate( T * _object, void (T::*_method)() )
  7. {
  8.     return new CMethodDelegate<T>(_object, _method);
  9. }

    至此,对C++函数指针的封装就完成了,不难吧。下面就是委托的实现了: 

点击(此处)折叠或打开

  1. class CMultiDelegate
  2. {
  3. public:
  4.     typedef std::list<IDelegate*> ListDelegate;
  5.     typedef ListDelegate::iterator ListDelegateIterator;
  6.     typedef ListDelegate::const_iterator ConstListDelegateIterator;

  7.     CMultiDelegate () { }
  8.     ~CMultiDelegate () { clear(); }

  9.     bool empty() const
  10.     {
  11.         for (ConstListDelegateIterator iter = mListDelegates.begin(); iter!=mListDelegates.end(); ++iter)
  12.         {
  13.             if (*iter) return false;
  14.         }
  15.         return true;
  16.     }

  17.     void clear()
  18.     {
  19.         for (ListDelegateIterator iter=mListDelegates.begin(); iter!=mListDelegates.end(); ++iter)
  20.         {
  21.             if (*iter)
  22.             {
  23.                 delete (*iter);
  24.                 (*iter) = 0;
  25.             }
  26.         }
  27.     }

  28.     CMultiDelegate& operator+=(IDelegate* _delegate)
  29.     {
  30.         for (ListDelegateIterator iter=mListDelegates.begin(); iter!=mListDelegates.end(); ++iter)
  31.         {
  32.             if ((*iter) && (*iter)->compare(_delegate))
  33.             {
  34.                 delete _delegate;
  35.                 return *this;
  36.             }
  37.         }
  38.         mListDelegates.push_back(_delegate);
  39.         return *this;
  40.     }

  41.     CMultiDelegate& operator-=(IDelegate* _delegate)
  42.     {
  43.         for (ListDelegateIterator iter=mListDelegates.begin(); iter!=mListDelegates.end(); ++iter)
  44.         {
  45.             if ((*iter) && (*iter)->compare(_delegate))
  46.             {
  47.                 if ((*iter) != _delegate) delete (*iter);
  48.                 (*iter) = 0;
  49.                 break;
  50.             }
  51.         }
  52.         delete _delegate;
  53.         return *this;
  54.     }

  55.     void operator()( )
  56.     {
  57.         ListDelegateIterator iter = mListDelegates.begin();
  58.         while (iter != mListDelegates.end())
  59.         {
  60.             if (0 == (*iter))
  61.             {
  62.                 iter = mListDelegates.erase(iter);
  63.             }
  64.             else
  65.             {
  66.                 (*iter)->invoke();
  67.                 ++iter;
  68.             }
  69.         }
  70.     }

  71. private:
  72.     CMultiDelegate (const CMultiDelegate& _event);
  73.     CMultiDelegate& operator=(const CMultiDelegate& _event);

  74. private:
  75.     ListDelegate mListDelegates;
  76. };

仔细理解下CMultiDelegate类的实现,代码都不深奥。

比较重要的是3个函数 +=-=()运算符的重载函数

+= 用于添加一个委托函数

-= 用于去掉一个委托函数

()用于触发委托函数

差不多就是普通的STL容器使用了。

这里要重点说明的一点是,大家仔细看 += 函数的实现中 

点击(此处)折叠或打开

  1. if ((*iter) && (*iter)->compare(_delegate))
  2. {
  3.     delete _delegate; // 如果该委托函数已经被添加了,则delete掉外部的_delegate
  4.     return *this;
  5. }

    为什么要delete掉外部的指针呢?因为C++的内存泄露一直是个麻烦事,所以MyUGI的委托里,所有的委托函数统一由Delegate本身管理,外部不要自己newdelete委托函数,也不要保存一个委托函数,Delegate本身会管理好的。建议像如下使用:

点击(此处)折叠或打开

  1. CMultiDelegate myDelegate;
  2. myDelegate += newDelegate(normalFunc);
  3. myDelegate -= newDelegate(normalFunc);
  4. //而不建议像如下使用:
  5. CMultiDelegate myDelegate;
  6. IDelegate* delegateFunc = newDelegate(normalFunc);
  7. myDelegate += delegateFunc;
  8. myDelegate -= delegateFunc;

    上面2种方法都没错,都不会造成内存泄露。你可能会觉得第2种方法减少new的次数,比第一种方法更好。其实不然,因为第2种方法有个很大的隐患,myDelegate -= delegateFunc; // 在这一步,delegateFunc所指向的空间已经被释放掉了(在-=函数里面),所以如果你后面又想将delegateFunc添加到myDelegate里面时,你就不能再这样用了。myDelegate += delegateFunc; // 错误,因为delegateFunc的空间已经被释放了。你得重新new一个:

delegateFunc = newDelegate(normalFunc);

myDelegate += delegateFunc;

       相信你不会愿意这样做的,因为这种方法很容易造成内存泄露或者崩溃,现在你应该可以明白 -= 函数是怎么释放委托函数内存了吧。按上面的方法,你已经可以使用无参数的函数委托了。下一篇文章将会介绍如何实现任意参数的函数委托。

阅读(3960) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~