用使用智能指针的Detach()方法真的不用引用计数了吗?
如下程序段:void UseStack()
{
  long i;
  IStopwatchStackPtr pStopwatchStack(__uuidof(StopwatchStack));
  IStopwatchPtr pStopwatch;
  IStopwatch * pIStopwatch=NULL;
  for(i=0;i<5;i++)
  {
    pStopwatch.CreateInstance(__uuidof(Stopwatch));
    pIStopwatch=pStopwatch.Detach();
    pStopwatchStack->Push(pIStopwatch);
  }
} //这个程序引用计数对吗?书上说:用Detach()方法不必再引用计数了。为什么?
如果说Detach()使智能指针中的m_pInterface = NULL;
那么引用计数应该由pIStopwatch负责。假设在UseStack()开始时,IStopwatch的引用为0,那么pStopwatch.CreateInstance(__uuidof(Stopwatch));为使IStopwatch的引用为1;在UseStack()结束时它会让引用计数减1(实际上在这里的条件下它没有).但是在程序中间,它把引用传给了pIStopwatch。那么为什么pIStopwatch不负责引用计数?如果说是由于pIStopwatch还是使用了pStopwatch的引用,那么如果pIStopwatch再把这个引用传给别的模块A,那么谁要负责引用计数是UseStack()中的pIStopwatch,还是模块A中的接口,什么时又卸载这个Stopwatch组件?在_com_ptr_t类的析构函数中:
~_com_ptr_t() throw()
{
_Release();
} void _Release() throw()
{
if (m_pInterface != NULL) {
m_pInterface->Release();
}
}在Detach()中:
Interface* Detach() throw()
{
Interface* const old=m_pInterface;
m_pInterface = NULL;
return old;
}
因此pStopwatch在构建时使引用计数加了1,但是由于在这里m_pInterface == NULL,所以它没有调用m_pInterface->Release();那么理论上应有pIStopwatch负责调用,在这个UseStack()函数中必没有这么做,
我认为至少在程序结束时要pIStopwatch->Release();