欢迎关注 [懒人漫说] 公众号,分享Java、Android、C/C++ 技术,
包括基础、自己遇到的问题解决过程。
当然如果关注并留言问题的话,我们力所能及的话会帮你解决并回复哟。我们和你一样,是正在成长的程序员,我们也会分享自己的成长路上的感想,希望可以和你一起努力成长。
// Copyright (C) 2007-2016 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library.
一、weak_ptr 的 lock() 函数原理
/* 当每次有新的 shared_ptr 生成时,会增加 _Sp_counted_base 的 _M_use_count (+1);
当每次有新的 weak_ptr 生成时,会增加 _Sp_counted_base 的 _M_weak_count (+1);
通过weak_ptr::lock()函数可以获取x对象的强引用(shared_ptr)。
对应的,shared_ptr 析构时,会调用 _Sp_counted_base 的 _M_release 来使 _M_use_count (-1);
weak_ptr 析构时,会调用 _Sp_counted_base 的 _M_release 来使 _M_weak_count (-1);
当 _M_use_count 的数量为 0 的时候 就会释放,原始的对象(用户自定义对象) 的内存,但是不会释放
_Sp_counted_base 的内存。
当 _M_use_count 和 _M_weak_count 都为 0的时候, 才会释放 _Sp_counted_base 的内存。
所以将一个普通指针赋值给两个不同的shared_ptr对象会引发double free。
eg:
int *n = new int(2);
shared_ptr pn1(n);
shared_ptr pn2(n);
// pn1 和 pn2 内部保存的指针都是n,而且内部引用计数都为1,所以在离开作用域的时候两个指针都会发生析构并释放指向的内存n。
尽量使用 shared_ptr pn = make_shared (2); 这种形式初始化一个shared_ptr指针。
*/
/*
* 此处引用 《Linux 多线程 服务端编程 使用 muduo C++ 网络库》 中对这两个智能指针的描述:
* 1 shared_ptr 控制对象的生命期。shared_ptr 是强引用,只要有一个指向x对象的shared_ptr存在,该x对象就不会
* 析构。当指向对象x的最后一个shared_ptr析构或reset()的时候,x保证会被销毁。
* 2 weak_ptr 不控制对象的生命期,但是它知道对象是否还活着。如果对象还活着,那么它可以提升(promote)为有效的
* shared_ptr; 如果对象已经死了,提升会失败,返回一个空的shared_ptr。“提升/lock()” 行为是线程安全的。
* 3 shared_ptr/weak_ptr 的“计数”在主流平台上是原子操作,没有用锁,性能不俗。
* 4 shared_ptr/weak_ptr 的线程安全级别与 std::string和STL容器一样。
*/
// __shared_count的构造函数会 new 一个 计数对象(_Sp_counted_base),但是__weak_count的构造函数不会new。
__shared_count(_Ptr __p) : _M_pi(0)
{
__try {
typedef typename std::tr1::remove_pointer<_Ptr>::type _Tp;
_M_pi = new _Sp_counted_base_impl<_Ptr, _Sp_deleter<_Tp>, _Lp>(
__p, _Sp_deleter<_Tp>());
} __catch(...) {
delete __p;
__throw_exception_again;
}
}
// lock 函数
__shared_ptr<_Tp, _Lp> lock() const // never throws
{
#ifdef __GTHREADS
// Optimization: avoid throw overhead.
if (expired())
return __shared_ptr();
__try {
return __shared_ptr(*this);
} __catch(const bad_weak_ptr&) {
return __shared_ptr();
}
#else
// Optimization: avoid try/catch overhead when single threaded.
return expired() ? __shared_ptr()
: __shared_ptr(*this);
#endif
} // XXX MT
bool expired() const // never throws
{
return _M_refcount._M_get_use_count() == 0;
}
三、下面源码有点长,不差资源分的话可以点击链接下载。
*注:所有的源码参看连接: http://download.csdn.net/download/u013005025/10155393
四、源码 (//version: Copyright © 2007-2016 Free Software Foundation, Inc.)
1 weak_ptr 源码
// weak_ptr
template
class weak_ptr
: public __weak_ptr < _Tp >
{
public:
weak_ptr()
: __weak_ptr<_Tp>() { }
template
weak_ptr(const weak_ptr<_Tp1>& __r)
: __weak_ptr<_Tp>(__r) { }
template
weak_ptr(const shared_ptr<_Tp1>& __r)
: __weak_ptr<_Tp>(__r) { }
template
weak_ptr&
operator=(const weak_ptr<_Tp1>& __r) // never throws
{
this->__weak_ptr<_Tp>::operator=(__r);
return *this;
}
template
weak_ptr& operator=(const shared_ptr<_Tp1>& __r) // never throws
{
this->__weak_ptr<_Tp>::operator=(__r);
return *this;
}
shared_ptr<_Tp> lock() const // never throws
{
#ifdef __GTHREADS
if (this->expired())
return shared_ptr<_Tp>();
__try{
return shared_ptr<_Tp>(*this);
}__catch(const bad_weak_ptr&){
return shared_ptr<_Tp>();
}
#else
return this->expired() ? shared_ptr<_Tp>()
: shared_ptr<_Tp>(*this);
#endif
}
};
2 __weak_ptr 源码
template
class __weak_ptr
{
public:
typedef _Tp element_type;
__weak_ptr() : _M_ptr(0), _M_refcount() // never throws
{ }
template
__weak_ptr(const __weak_ptr<_Tp1, _Lp>& __r)
: _M_refcount(__r._M_refcount) // never throws
{
__glibcxx_function_requires(_ConvertibleConcept<_Tp1*, _Tp*>)
_M_ptr = __r.lock().get();
}
template
__weak_ptr(const __shared_ptr<_Tp1, _Lp>& __r)
: _M_ptr(__r._M_ptr), _M_refcount(__r._M_refcount) // never throws
{
__glibcxx_function_requires(_ConvertibleConcept<_Tp1*, _Tp*>)
}
template
__weak_ptr& operator=(const __weak_ptr<_Tp1, _Lp>& __r) // never throws
{
_M_ptr = __r.lock().get();
_M_refcount = __r._M_refcount;
return *this;
}
template
__weak_ptr& operator=(const __shared_ptr<_Tp1, _Lp>& __r) // never throws
{
_M_ptr = __r._M_ptr;
_M_refcount = __r._M_refcount;
return *this;
}
__shared_ptr<_Tp, _Lp> lock() const // never throws
{
#ifdef __GTHREADS
// Optimization: avoid throw overhead.
if (expired())
return __shared_ptr();
__try {
return __shared_ptr(*this);
} __catch(const bad_weak_ptr&) {
return __shared_ptr();
}
#else
// Optimization: avoid try/catch overhead when single threaded.
return expired() ? __shared_ptr()
: __shared_ptr(*this);
#endif
} // XXX MT
long use_count() const // never throws
{
return _M_refcount._M_get_use_count();
}
bool expired() const // never throws
{
return _M_refcount._M_get_use_count() == 0;
}
void reset() // never throws
{
__weak_ptr().swap(*this);
}
void swap(__weak_ptr& __s) // never throws
{
std::swap(_M_ptr, __s._M_ptr);
_M_refcount._M_swap(__s._M_refcount);
}
private:
// Used by __enable_shared_from_this.
void _M_assign(_Tp* __ptr, const __shared_count<_Lp>& __refcount)
{
_M_ptr = __ptr;
_M_refcount = __refcount;
}
template
bool _M_less(const __weak_ptr<_Tp1, _Lp>& __rhs) const
{
return _M_refcount < __rhs._M_refcount;
}
template friend class __shared_ptr;
template friend class __weak_ptr;
friend class __enable_shared_from_this < _Tp, _Lp > ;
friend class enable_shared_from_this < _Tp > ;
// Friend injected into namespace and found by ADL.
template
friend inline bool
operator<(const __weak_ptr& __lhs, const __weak_ptr<_Tp1, _Lp>& __rhs)
{
return __lhs._M_less(__rhs);
}
_Tp* _M_ptr; // Contained pointer.
__weak_count<_Lp> _M_refcount; // Reference counter.
};
3 __weak_count 源码
template<_Lock_policy _Lp>
class __weak_count
{
public:
__weak_count() : _M_pi(0) // nothrow
{ }
__weak_count(const __shared_count<_Lp>& __r)
: _M_pi(__r._M_pi) // nothrow
{
if (_M_pi != 0)
_M_pi->_M_weak_add_ref();
}
__weak_count(const __weak_count<_Lp>& __r)
: _M_pi(__r._M_pi) // nothrow
{
if (_M_pi != 0)
_M_pi->_M_weak_add_ref();
}
~__weak_count() // nothrow
{
if (_M_pi != 0)
_M_pi->_M_weak_release();
}
__weak_count<_Lp>& operator=(const __shared_count<_Lp>& __r) // nothrow
{
_Sp_counted_base<_Lp>* __tmp = __r._M_pi;
if (__tmp != 0)
__tmp->_M_weak_add_ref();
if (_M_pi != 0)
_M_pi->_M_weak_release();
_M_pi = __tmp;
return *this;
}
__weak_count<_Lp>& operator=(const __weak_count<_Lp>& __r) // nothrow
{
_Sp_counted_base<_Lp>* __tmp = __r._M_pi;
if (__tmp != 0)
__tmp->_M_weak_add_ref();
if (_M_pi != 0)
_M_pi->_M_weak_release();
_M_pi = __tmp;
return *this;
}
void _M_swap(__weak_count<_Lp>& __r) // nothrow
{
_Sp_counted_base<_Lp>* __tmp = __r._M_pi;
__r._M_pi = _M_pi;
_M_pi = __tmp;
}
long _M_get_use_count() const // nothrow
{
return _M_pi != 0 ? _M_pi->_M_get_use_count() : 0;
}
friend inline bool
operator==(const __weak_count<_Lp>& __a, const __weak_count<_Lp>& __b)
{
return __a._M_pi == __b._M_pi;
}
friend inline bool
operator<(const __weak_count<_Lp>& __a, const __weak_count<_Lp>& __b)
{
return std::less<_Sp_counted_base<_Lp>*>()(__a._M_pi, __b._M_pi);
}
private:
friend class __shared_count < _Lp > ;
_Sp_counted_base<_Lp>* _M_pi;
};
五、shared_ptr 源码
// The actual shared_ptr, with forwarding constructors and
// assignment operators.
// shared_ptr
template
class shared_ptr
: public __shared_ptr < _Tp >
{
public:
shared_ptr()
: __shared_ptr<_Tp>() { }
template
explicit
shared_ptr(_Tp1* __p)
: __shared_ptr<_Tp>(__p) { }
template
shared_ptr(_Tp1* __p, _Deleter __d)
: __shared_ptr<_Tp>(__p, __d) { }
template
shared_ptr(const shared_ptr<_Tp1>& __r)
: __shared_ptr<_Tp>(__r) { }
template
explicit
shared_ptr(const weak_ptr<_Tp1>& __r)
: __shared_ptr<_Tp>(__r) { }
#if (__cplusplus < 201103L) || _GLIBCXX_USE_DEPRECATED
template
explicit
shared_ptr(std::auto_ptr<_Tp1>& __r)
: __shared_ptr<_Tp>(__r) { }
#endif
template
shared_ptr(const shared_ptr<_Tp1>& __r, __static_cast_tag)
: __shared_ptr<_Tp>(__r, __static_cast_tag()) { }
template
shared_ptr(const shared_ptr<_Tp1>& __r, __const_cast_tag)
: __shared_ptr<_Tp>(__r, __const_cast_tag()) { }
template
shared_ptr(const shared_ptr<_Tp1>& __r, __dynamic_cast_tag)
: __shared_ptr<_Tp>(__r, __dynamic_cast_tag()) { }
template
shared_ptr& operator=(const shared_ptr<_Tp1>& __r) // never throws
{
this->__shared_ptr<_Tp>::operator=(__r);
return *this;
}
#if (__cplusplus < 201103L) || _GLIBCXX_USE_DEPRECATED
template
shared_ptr& operator=(std::auto_ptr<_Tp1>& __r)
{
this->__shared_ptr<_Tp>::operator=(__r);
return *this;
}
#endif
};
// __shared_ptr
struct __static_cast_tag { };
struct __const_cast_tag { };
struct __dynamic_cast_tag { };
// A smart pointer with reference-counted copy semantics. The
// object pointed to is deleted when the last shared_ptr pointing to
// it is destroyed or reset.
template
class __shared_ptr
{
public:
typedef _Tp element_type;
__shared_ptr()
: _M_ptr(0), _M_refcount() // never throws
{ }
template
explicit __shared_ptr(_Tp1* __p)
: _M_ptr(__p), _M_refcount(__p)
{
__glibcxx_function_requires(_ConvertibleConcept<_Tp1*, _Tp*>)
typedef int _IsComplete[sizeof(_Tp1)];
__enable_shared_from_this_helper(_M_refcount, __p, __p);
}
template
__shared_ptr(_Tp1* __p, _Deleter __d)
: _M_ptr(__p), _M_refcount(__p, __d)
{
__glibcxx_function_requires(_ConvertibleConcept<_Tp1*, _Tp*>)
// TODO requires _Deleter CopyConstructible and __d(__p) well-formed
__enable_shared_from_this_helper(_M_refcount, __p, __p);
}
// generated copy constructor, assignment, destructor are fine.
template
__shared_ptr(const __shared_ptr<_Tp1, _Lp>& __r)
: _M_ptr(__r._M_ptr), _M_refcount(__r._M_refcount) // never throws
{
__glibcxx_function_requires(_ConvertibleConcept<_Tp1*, _Tp*>)
}
template
explicit
__shared_ptr(const __weak_ptr<_Tp1, _Lp>& __r)
: _M_refcount(__r._M_refcount) // may throw
{
__glibcxx_function_requires(_ConvertibleConcept<_Tp1*, _Tp*>)
// It is now safe to copy __r._M_ptr, as _M_refcount(__r._M_refcount)
// did not throw.
_M_ptr = __r._M_ptr;
}
#if (__cplusplus < 201103L) || _GLIBCXX_USE_DEPRECATED
// Postcondition: use_count() == 1 and __r.get() == 0
template
explicit __shared_ptr(std::auto_ptr<_Tp1>& __r)
: _M_ptr(__r.get()), _M_refcount()
{ // TODO requries delete __r.release() well-formed
__glibcxx_function_requires(_ConvertibleConcept<_Tp1*, _Tp*>)
typedef int _IsComplete[sizeof(_Tp1)];
_Tp1* __tmp = __r.get();
_M_refcount = __shared_count<_Lp>(__r);
__enable_shared_from_this_helper(_M_refcount, __tmp, __tmp);
}
#endif
template
__shared_ptr(const __shared_ptr<_Tp1, _Lp>& __r, __static_cast_tag)
: _M_ptr(static_cast(__r._M_ptr)),
_M_refcount(__r._M_refcount)
{ }
template
__shared_ptr(const __shared_ptr<_Tp1, _Lp>& __r, __const_cast_tag)
: _M_ptr(const_cast(__r._M_ptr)),
_M_refcount(__r._M_refcount)
{ }
template
__shared_ptr(const __shared_ptr<_Tp1, _Lp>& __r, __dynamic_cast_tag)
: _M_ptr(dynamic_cast(__r._M_ptr)),
_M_refcount(__r._M_refcount)
{
if (_M_ptr == 0) // need to allocate new counter -- the cast failed
_M_refcount = __shared_count<_Lp>();
}
template
__shared_ptr& operator=(const __shared_ptr<_Tp1, _Lp>& __r) // never throws
{
_M_ptr = __r._M_ptr;
_M_refcount = __r._M_refcount; // __shared_count::op= doesn't throw
return *this;
}
#if (__cplusplus < 201103L) || _GLIBCXX_USE_DEPRECATED
template
__shared_ptr& operator=(std::auto_ptr<_Tp1>& __r)
{
__shared_ptr(__r).swap(*this);
return *this;
}
#endif
void reset() // never throws
{
__shared_ptr().swap(*this);
}
template
void reset(_Tp1* __p) // _Tp1 must be complete.
{
// Catch self-reset errors.
_GLIBCXX_DEBUG_ASSERT(__p == 0 || __p != _M_ptr);
__shared_ptr(__p).swap(*this);
}
template
void reset(_Tp1* __p, _Deleter __d)
{
__shared_ptr(__p, __d).swap(*this);
}
// Allow class instantiation when _Tp is [cv-qual] void.
typename std::tr1::add_reference<_Tp>::type
operator*() const // never throws
{
_GLIBCXX_DEBUG_ASSERT(_M_ptr != 0);
return *_M_ptr;
}
_Tp* operator->() const // never throws
{
_GLIBCXX_DEBUG_ASSERT(_M_ptr != 0);
return _M_ptr;
}
_Tp* get() const // never throws
{
return _M_ptr;
}
// Implicit conversion to "bool"
private:
typedef _Tp* __shared_ptr::*__unspecified_bool_type;
public:
operator __unspecified_bool_type() const // never throws
{
return _M_ptr == 0 ? 0 : &__shared_ptr::_M_ptr;
}
bool unique() const // never throws
{
return _M_refcount._M_unique();
}
long use_count() const // never throws
{
return _M_refcount._M_get_use_count();
}
void swap(__shared_ptr<_Tp, _Lp>& __other) // never throws
{
std::swap(_M_ptr, __other._M_ptr);
_M_refcount._M_swap(__other._M_refcount);
}
private:
void* _M_get_deleter(const std::type_info& __ti) const
{
return _M_refcount._M_get_deleter(__ti);
}
template
bool _M_less(const __shared_ptr<_Tp1, _Lp1>& __rhs) const
{
return _M_refcount < __rhs._M_refcount;
}
template friend class __shared_ptr;
template friend class __weak_ptr;
template
friend _Del* get_deleter(const __shared_ptr<_Tp1, _Lp1>&);
// Friends injected into enclosing namespace and found by ADL:
template
friend inline bool
operator==(const __shared_ptr& __a, const __shared_ptr<_Tp1, _Lp>& __b)
{
return __a.get() == __b.get();
}
template
friend inline bool
operator!=(const __shared_ptr& __a, const __shared_ptr<_Tp1, _Lp>& __b)
{
return __a.get() != __b.get();
}
template
friend inline bool
operator<(const __shared_ptr& __a, const __shared_ptr<_Tp1, _Lp>& __b)
{
return __a._M_less(__b);
}
_Tp* _M_ptr; // Contained pointer.
__shared_count<_Lp> _M_refcount; // Reference counter.
};
// __shared_count
template<_Lock_policy _Lp = __default_lock_policy>
class __shared_count
{
public:
__shared_count()
: _M_pi(0) // nothrow
{ }
template
__shared_count(_Ptr __p) : _M_pi(0)
{
__try
{
typedef typename std::tr1::remove_pointer<_Ptr>::type _Tp;
_M_pi = new _Sp_counted_base_impl<_Ptr, _Sp_deleter<_Tp>, _Lp>(
__p, _Sp_deleter<_Tp>());
}
__catch(...)
{
delete __p;
__throw_exception_again;
}
}
template
__shared_count(_Ptr __p, _Deleter __d) : _M_pi(0)
{
__try
{
_M_pi = new _Sp_counted_base_impl<_Ptr, _Deleter, _Lp>(__p, __d);
}
__catch(...)
{
__d(__p); // Call _Deleter on __p.
__throw_exception_again;
}
}
// Special case for auto_ptr<_Tp> to provide the strong guarantee.
template
explicit
__shared_count(std::auto_ptr<_Tp>& __r)
: _M_pi(new _Sp_counted_base_impl < _Tp*,
_Sp_deleter<_Tp>, _Lp > (__r.get(), _Sp_deleter<_Tp>()))
{
__r.release();
}
// Throw bad_weak_ptr when __r._M_get_use_count() == 0.
explicit __shared_count(const __weak_count<_Lp>& __r);
~__shared_count() // nothrow
{
if (_M_pi != 0)
_M_pi->_M_release();
}
__shared_count(const __shared_count& __r)
: _M_pi(__r._M_pi) // nothrow
{
if (_M_pi != 0)
_M_pi->_M_add_ref_copy();
}
__shared_count& operator=(const __shared_count& __r) // nothrow
{
_Sp_counted_base<_Lp>* __tmp = __r._M_pi;
if (__tmp != _M_pi)
{
if (__tmp != 0)
__tmp->_M_add_ref_copy();
if (_M_pi != 0)
_M_pi->_M_release();
_M_pi = __tmp;
}
return *this;
}
void _M_swap(__shared_count& __r) // nothrow
{
_Sp_counted_base<_Lp>* __tmp = __r._M_pi;
__r._M_pi = _M_pi;
_M_pi = __tmp;
}
long _M_get_use_count() const // nothrow
{
return _M_pi != 0 ? _M_pi->_M_get_use_count() : 0;
}
bool _M_unique() const // nothrow
{
return this->_M_get_use_count() == 1;
}
friend inline bool
operator==(const __shared_count& __a, const __shared_count& __b)
{
return __a._M_pi == __b._M_pi;
}
friend inline bool
operator<(const __shared_count& __a, const __shared_count& __b)
{
return std::less<_Sp_counted_base<_Lp>*>()(__a._M_pi, __b._M_pi);
}
void* _M_get_deleter(const std::type_info& __ti) const
{
return _M_pi ? _M_pi->_M_get_deleter(__ti) : 0;
}
private:
friend class __weak_count < _Lp > ;
_Sp_counted_base<_Lp>* _M_pi;
};
// _Sp_counted_base
template<_Lock_policy _Lp = __default_lock_policy>
class _Sp_counted_base
: public _Mutex_base < _Lp >
{
public:
_Sp_counted_base()
: _M_use_count(1), _M_weak_count(1) { }
virtual ~_Sp_counted_base() // nothrow
{ }
// Called when _M_use_count drops to zero, to release the resources
// managed by *this.
virtual void _M_dispose() = 0; // nothrow
// Called when _M_weak_count drops to zero.
virtual void _M_destroy() // nothrow
{
delete this;
}
virtual void* _M_get_deleter(const std::type_info&) = 0;
void _M_add_ref_copy()
{
__gnu_cxx::__atomic_add_dispatch(&_M_use_count, 1);
}
void _M_add_ref_lock();
void _M_release() // nothrow
{
// Be race-detector-friendly. For more info see bits/c++config.
_GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(&_M_use_count);
if (__gnu_cxx::__exchange_and_add_dispatch(&_M_use_count, -1) == 1)
{
_GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(&_M_use_count);
_M_dispose();
// There must be a memory barrier between dispose() and destroy()
// to ensure that the effects of dispose() are observed in the
// thread that runs destroy().
// See https://gcc.gnu.org/ml/libstdc++/2005-11/msg00136.html
if (_Mutex_base<_Lp>::_S_need_barriers)
{
__atomic_thread_fence(__ATOMIC_ACQ_REL);
}
// Be race-detector-friendly. For more info see bits/c++config.
_GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(&_M_weak_count);
if (__gnu_cxx::__exchange_and_add_dispatch(&_M_weak_count,
-1) == 1)
{
_GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(&_M_weak_count);
_M_destroy();
}
}
}
void _M_weak_add_ref() // nothrow
{
__gnu_cxx::__atomic_add_dispatch(&_M_weak_count, 1);
}
void _M_weak_release() // nothrow
{
// Be race-detector-friendly. For more info see bits/c++config.
_GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(&_M_weak_count);
if (__gnu_cxx::__exchange_and_add_dispatch(&_M_weak_count, -1) == 1)
{
_GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(&_M_weak_count);
if (_Mutex_base<_Lp>::_S_need_barriers)
{
// See _M_release(),
// destroy() must observe results of dispose()
__atomic_thread_fence(__ATOMIC_ACQ_REL);
}
_M_destroy();
}
}
long _M_get_use_count() const // nothrow
{
// No memory barrier is used here so there is no synchronization
// with other threads.
return const_cast(_M_use_count);
}
private:
_Sp_counted_base(_Sp_counted_base const&);
_Sp_counted_base& operator=(_Sp_counted_base const&);
_Atomic_word _M_use_count; // #shared
_Atomic_word _M_weak_count; // #weak + (#shared != 0)
};
End ----------------------------------------------------------------------------------------------------