问:智能指针能够对指针的引用数量进行计数,一个智能指针释放时,别的智能指针怎么知道的?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就把原始指针对应的内存释放,同时销毁计数的类。内存