// _MT_INCR 和 _MT_DECR是宏,對應的API函數爲InterlockedIncrement/InterlockedDecrement,功能爲對變量加一或減一,特點是線程安全,即它們在多線程下能保證執行結果正確。
// CLASS _Ref_count_base 引用計數輔助基類(增加、減少引用計數用上述宏實現,而不是單純的++,--)
class _Ref_count_base
{ // common code for reference counting 引用計數通用代碼
private:
virtual void _Destroy() = 0; // 銷燬託管資源(後續派生類的成員指針變量)
virtual void _Delete_this() = 0; // 銷燬自身(delete this;)
private:
_Atomic_counter_t _Uses; // 原子計數器(Uses),其實就是uint_32
_Atomic_counter_t _Weaks; // 弱引用計數
protected:
_Ref_count_base()
{ // construct
_Init_atomic_counter(_Uses, 1); // 將_Uses、_Weaks初始化爲1,非原子初始化計數器
_Init_atomic_counter(_Weaks, 1);
}
public:
virtual ~_Ref_count_base() _NOEXCEPT
{ // ensure that derived classes can be destroyed properly 確保派生類可以正確銷燬
}
// 如果不爲零,則增加使用計數_Uses;如果成功,則返回true
bool _Incref_nz()
{ // increment use count if not zero, return true if successful
for (;;)
{ // loop until state is known
#if defined(_M_IX86) || defined(_M_X64) || defined(_M_CEE_PURE)
_Atomic_integral_t _Count =
static_cast<volatile _Atomic_counter_t&>(_Uses);//volatile申明指令不會被優化而省略
if (_Count == 0)
return (false);
//InterlockedCompareExchange是把第1參數 與 第3參數 比較,如果相等,則用 第2參數 與 第1參數 交換;返回子爲_Uses的初值
if (static_cast<_Atomic_integral_t>(_InterlockedCompareExchange(
reinterpret_cast<volatile long *>(&_Uses),
_Count + 1, _Count)) == _Count)
return (true);
#else /* defined(_M_IX86) || defined(_M_X64) || defined(_M_CEE_PURE) */
_Atomic_integral_t _Count =
_Load_atomic_counter(_Uses);
if (_Count == 0)
return (false);
if (_Compare_increment_atomic_counter(_Uses, _Count))
return (true);
#endif
}
}
// Get _Uses值
unsigned int _Get_uses() const
{ // return use count
return (_Get_atomic_count(_Uses));
}
// 遞增引用計數_Uses
void _Incref()
{ // increment use count
_MT_INCR(_Mtx, _Uses);// 實現數的原子性加
}
// 遞增弱引用計數_Weaks
void _Incwref()
{ // increment weak reference count
_MT_INCR(_Mtx, _Weaks);
}
// 減少引用計數_Uses
void _Decref()
{ // decrement use count
if (_MT_DECR(_Mtx, _Uses) == 0)// 實現數的原子性減
{ // destroy managed resource, decrement weak reference count 銷燬託管資源,減少弱引用計數
_Destroy();
_Decwref();
}
}
// 減少弱引用計數_Weaks
void _Decwref()
{ // decrement weak reference count
if (_MT_DECR(_Mtx, _Weaks) == 0) // 當弱引用計數爲0是,釋放對象
_Delete_this();
}
// Get _Uses值
long _Use_count() const
{ // return use count
return (_Get_uses());
}
// 判斷引用計數_Uses是否爲0
bool _Expired() const
{ // return true if _Uses == 0
return (_Get_uses() == 0);
}
virtual void *_Get_deleter(const _XSTD2 type_info&) const
{ // return address of deleter object 返回刪除對象的地址
return (0);
}
};
// 其所有的派生類都會再定義一個同 智能指針基類_Ptr_base中的存儲元素數據 一樣的成員變量_Ty *_Ptr,共同指向數據單元的內存地址,用於管理內存。當引用計數變爲0時釋放該內存(調用_Destroy())。