歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C++實現的委托機制

C++實現的委托機制

日期:2017/3/1 10:12:14   编辑:Linux編程

1.引言

下面的委托實現使用的MyGUI裡面的委托實現,MyGUI是一款強大的GUI庫,想理解更多的MyGUI信息,猛擊這裡。

我們的目標是要實現一個跟.NET幾乎完全一樣的委托,使用簡單,支持多播,可以添加刪除委托。同時支持C++的普通函數、模板函數、類成員函數,類的靜態成員函數,並且支持多態。

最終的代碼可以在這裡下載:

免費下載地址在 http://linux.linuxidc.com/

用戶名與密碼都是www.linuxidc.com

具體下載目錄在 /2012年資料/8月/19日/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. myDelegate -= newDelegate(&b, &Base::classFunc);
  17. myDelegate(); // 此時會調用normalFunc
  18. return 0;
  19. }

2.實現無參函數委托

要實現委托,首先要解決的是封裝C++中的函數指針。因為在C++中,普通函數指針和類成員函數指針是完全不一樣的。如下例子

  1. class CMyClass
  2. {
  3. public:
  4. void func(int);
  5. };
  6. // 定義一個指向CMyClass類型,參數列表為(int),返回值為void的函數指針
  7. 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,用於觸發函數

但為了可以方便管理,使用了isType和compare函數來進行相等判斷。

下面是封裝的普通函數指針

  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只是簡單地封裝了普通函數指針,代碼也非常簡單

(類的某些成員函數,如isType和compare使用了RTTI,

對C++的動態類型判斷不熟的可以猛擊這裡 http://www.linuxidc.com/Linux/2012-08/68655.htm )

好了,注意��,下面開始封裝類成員函數指針

  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本身管理

外部不要自己new或delete委托函數,也不要保存一個委托函數,Delegate本身會管理好的。

建議像如下使用:

  1. CMultiDelegate myDelegate;
  2. myDelegate += newDelegate(normalFunc);
  3. myDelegate -= newDelegate(normalFunc);

而不建議像如下使用:

  1. CMultiDelegate myDelegate;
  2. IDelegate* delegateFunc = newDelegate(normalFunc);
  3. myDelegate += delegateFunc;
  4. myDelegate -= delegateFunc;

上面2種方法都沒錯,都不會造成內存洩露

你可能會覺得第2種方法減少new的次數,比第一種方法更好。其實不然,因為第2種方法有個很大的隱患

  1. myDelegate -= delegateFunc; // 在這一步,delegateFunc所指向的空間已經被釋放掉了(在-=函數裡面)

所以如果你後面又想將delegateFunc添加到myDelegate裡面時,你就不能再這樣用了

  1. myDelegate += delegateFunc; // 錯誤,因為delegateFunc的空間已經被釋放了
你得重新new一個

delegateFunc = newDelegate(normalFunc);

myDelegate += delegateFunc;

相信你不會願意這樣做的,因為這種方法很容易造成內存洩露或者崩潰

現在你應該可以明白 -= 函數是怎麼釋放委托函數內存了吧。

按上面的方法,你已經可以使用無參數的函數委托了。下一篇文章將會介紹如何實現任意參數的函數委托。

Copyright © Linux教程網 All Rights Reserved