問:智能指針能夠對指針的引用數量進行計數,一個智能指針釋放時,別的智能指針怎麼知道的?app
同一類的對象共享同一變量最簡單的方法是靜態變量:ide
不像普通的變量,靜態成員變量是被全部類對象共享的,不一樣的對象能夠訪問對方的該靜態成員變量,所以靜態成員變量和類對象並無聯繫。函數
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 objectsthis
可是智能指針shared_ptr並非用的靜態變量。指針
模板類__shared_ptr
有兩個成員變量和一堆的函數:rest
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
是一個模板類,除了一大堆成員函數外有一個類變量:code
template <_Lock_policy _Lp> class __shared_count { // 省略一堆函數 _Sp_counted_base<_Lp>* _M_pi; };
進一步可知:orm
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就把原始指針對應的內存釋放,同時銷燬計數的類。內存