問:智能指針可以對指針的引用數量進行計數,一個智能指針釋放時,別的智能指針怎么知道的?
同一類的對象共享同一變量最簡單的方法是靜態變量:
不像普通的變量,靜態成員變量是被所有類對象共享的,不同的對象可以訪問對方的該靜態成員變量,因此靜態成員變量和類對象並沒有聯系。
The static keyword has another meaning when applied to global variables -- it gives them internal linkage (which restricts them from being seen/used outside of the file they are defined in). Because global variables are typically avoided, the static keyword is not often used in this capacity.
Unlike normal member variables, static member variables are shared by all objects of the class.Static members are not associated with class objects
但是智能指針shared_ptr並不是用的靜態變量。
模板類__shared_ptr
有兩個成員變量和一堆的函數:
template<_Lock_policy _Lp>
class __shared_ptr : public __shared_ptr_access<_Tp, _Lp>
{
// 省略一堆函數和操作符重載
element_type* _M_ptr; // Contained pointer.
__shared_count<_Lp> _M_refcount; // Reference counter.
};
然后__shared_count
是一個模板類,除了一大堆成員函數外有一個類變量:
template <_Lock_policy _Lp>
class __shared_count
{
// 省略一堆函數
_Sp_counted_base<_Lp>* _M_pi;
};
進一步可知:
template<_Lock_policy _Lp = __default_lock_policy>
class _Sp_counted_base
: public _Mutex_base<_Lp>
{
// 省略一堆函數
_Atomic_word _M_use_count; // #shared
_Atomic_word _M_weak_count; // #weak + (#shared != 0)
};
而_Atomic_word
就是int:
typedef int _Atomic_word;
所以,shared_ptr的引用計數實現機制,簡單地說就是:
同一個指針的所有shared_ptr的計數值是共享的,這個計數值包含在一個類里面,該原始指針的所有shared_ptr都引用這個計數的類,當一個智能指針銷毀時,就讓計數的類去把計數值減1,如果值為0就把原始指針對應的內存釋放,同時銷毀計數的類。