4.2. Traditional Memory De-allocation Schemas
.NET在释放内存和销毁对象上不同于C++、COM。在C++中,一个基于栈的对象离开声明范围时将会销毁:
{//beginning of a C++ scope
MyClass object;
//use object;
}//end of scope, C++ calls the object destructor
同样,在C++中使用delete操作符也会销毁对象:
MyClass* pObject = new MyClass;
//using pObject, then de-allocating it
delete pObject;
COM使用了引用计数,它会根据客户端增加或减少一个对象的计数器。当客户端共享一个对象时,调用AddRef( )增加计数器。新的COM对象在创建时计数为1。当客户端使用完一个对象后,调用Release( )减少该计数器:
//COM pseudo-code:
IMyInterface* pObject = NULL;
::CoCreateInstance(CLSID_MyClass,IID_IMyInterface,&pObject);
//using pObject, then releasing it
pObject->Release( );
当一个计数等于0时,这个对象将会销毁:
//COM implementation of IUnknown::Release( )
ULONG MyClass::Release( )
{
//m_Counter is this class counter
m_Counter--;
if(m_Counter == 0)
{
delete this;
return 0;
}
//Should return the counter:
return m_Counter;
}