对象生命期管理系统

王朝other·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

5.对象生命期管理系统

//第一个参数接口类,第二个参数具体类

template<class I,class C>//接口指针模板

class SIP{

public:

//从实现类的一个接口映射到另一个接口

template<class I2>

SIP<I2,C> Cast()

{

return SIP<I2,C>(_c);

}

explicit

//从一个已经存在(带参构造)的具体类,映射到智能接口指针

SIP(C * c):_c(c){

_i=static_cast<I *>(c);

_i->AddRef();

};

//无参构造,用于具体类 没有构造函数的情况

explicit

SIP():{

_c=new C;

_i=static_cast<T *>(_c);

_i->AddRef();

};

SIP(SIP<I,C> & p){ //CCTOR

_i=p.get();

_c=p.get2();

_i->AddRef();

cout<<"cctor"<<endl;

cout<<_i->ct();

};

SIP<I,C>& operator=(SIP<I,C> & p)

{

_i=p.get();

_c=p.get2();

_i->AddRef();

cout<<"operator ="<<endl;

cout<<_i->ct();

};

I & operator*() const

{// return designated value

return (*_i);

}

I *operator->() const

{// return pointer to class object

return (&**this);

}

I *get() const

{// return wrapped pointer

return (_i);

}

C *get2() const

{// return wrapped pointer

return (_c);

}

~SIP()

{

_i->Release();

};

private:

I * _i; //接口指针

C * _c;//具体类指针

};

template<class I,class C> //把一个具体类的指针映射到一个智能接口指针 SIP

SIP<I,C> Cast(C * c)

{

return SIP<I,C>(c);

};

interface IUnknown{

virtual int AddRef( void) = 0;

virtual int Release( void) = 0;

};

#define DECLARE_IUNKNOWN()public:virtual int AddRef( void){count++;return 0;};virtual int Release( void){count--;if (count==0) {delete this;}return 0;};public:int count;

main.cpp

#include "stdafx.h"

#include "global_datastruct.h"

#include "SentenceManager.h"

using namespace std;

typedef SIP<ISentenceManager,CSentenceManager> PISentenceManager

PISentenceManager a()

{

CSentenceManager * ps=new CSentenceManager ;//带构造参数的具体类(指针)

PISentenceManager p=Cast<ISentenceManager>(ps);//映射到一个SIP

cout<<"ct:";

cout<<ps->count;

return PISentenceManager(p);//构造一个临时的SIP

}

void b()

{

PISentenceManager p(a()); //用一个临时的SIP构造一个新的SIP

PISentenceManager p2=p; //用一个SIP对另一个SIP赋值

cout<<"ct:";

cout<<p->ct();

p2->Display_the_sentence();

//接口映射,将一个内含一个接口的SIP中的接口,映射到对象支持的另一个接口

typedef SIP<I2,CSentenceManager> PI2

PI2 pp=p.Cast<I2>();

cout<<"ct:";

pp->show();

}

int _tmain(int argc, _TCHAR* argv[])

{

b();

int x;

cin>>x;

return 0;

}

输出:

ct:1copy construct

2copy construct

2ct:2do shmeying on CSentenceManager

0012FCD4

ct:T2

ct:0

destoried

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航