我正在学习COM并阅读有关此代码的内容:
STDMETHODIMP_ (ULONG) ComCar::Release()
{
if(--m_refCount==0) delete this;
return m_refCount;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,如果m_refCount == 0并删除了对象,实例成员变量m_refCount如何仍然存在并返回?如果我的问题太天真,请原谅我,因为我是COM的新手.非常感谢.
一个相关的线程在这里:成员方法如何删除对象?
您的问题是有效的,在删除对象之前,应将引用计数移动到局部变量中.
STDMETHODIMP_ (ULONG) ComCar::Release()
{
ULONG refCount = --m_refCount; // not thread safe
if(refcount==0) delete this;
return refCount;
}
Run Code Online (Sandbox Code Playgroud)
但即使代码仍然是错误的,因为它不是线程安全的.
你应该使用这样的代码.
STDMETHODIMP_ (ULONG) ComCar::Release()
{
LONG cRefs = InterlockedDecrement((LONG*)&m_refCount);
if (0 == cRefs) delete this;
return (ULONG)max(cRefs, 0);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1051 次 |
| 最近记录: |