c++智能指针介绍之weak_ptr
c++11引入,头文件在<memory>
,主要是用来协助shared_ptr
,不占用引用计数值。
特性:
弱引用,不占用引用计数值 lock/``expired
/use_count
/opreater=
没有重载operater*
和operator->
use_count
: 返回共享对象shared_ptr
的引用计数值expired
: 如果use_count
返回0,则expired
返回为true
lock
:如果expired
返回true
,则lock
返回一个空指针;否则返回一个指向对象的shared_ptr
并增加对象的引用计数值。
weak_ptr& operator= ( const weak_ptr& r ) noexcept;
template< class Y > weak_ptr& operator= ( const weak_ptr< Y> & r ) noexcept;
weak_ptr& operator= ( const shared_ptr< Y> & r ) noexcept;
weak_ptr& operator= ( weak_ptr&& r ) noexcept;
template< class Y > weak_ptr& operator= ( weak_ptr< Y> && r ) noexcept;
解决循环引用问题
类A中包含有类B的智能指针成员, 类B中包含有类A的之智能指针成员,当类A、B分别实例化并交由智能指针对象管理 且 将各自赋值给独享的内部智能指针,则会出现循环引用,导致最后的类AB资源释放不成功; 将类中的shared_ptr
换成weak_ptr
就能解决循环引用问题。
class A {
public:
shared_ptr< B> bp;
}
class B {
public:
shared_ptr< A> ap;
}
shared_ptr< A> asp ( new A ( ) ) ;
shared_ptr< B> bsp ( new B ( ) ) ;
asp-> bp = bsp;
bsp-> ap = asp;
enable_shared_from_this
使用场景: 单某个类已经被shared_ptr
修饰,且调用者不想在新增控制块(共用原来的控制块)时,将这个类继承enable_share_from_this
, 在特定的成员函数中使用shared_from_this
返回共享这个对象的shared_ptr
对象。适用于类对象已经被某个智能指针引用,但是不知道这个智能指针,通过裸指针反推出这个引用的智能指针
,如果已经知道则可以直接用已知的智能指针给新的智能指针赋值来共用一个资源。
# include <memory>
# include <iostream>
struct Good : std:: enable_shared_from_this< Good>
{
std:: shared_ptr< Good> getptr ( ) {
return shared_from_this ( ) ;
}
} ;
struct Bad
{
std:: shared_ptr< Bad> getptr ( ) {
return std:: shared_ptr< Bad> ( this) ;
}
~ Bad ( ) { std:: cout << "Bad::~Bad() called\n" ; }
} ;
int main ( )
{
std:: shared_ptr< Good> gp1 = std:: make_shared< Good> ( ) ;
std:: shared_ptr< Good> gp2 = gp1-> getptr ( ) ;
std:: cout << "gp2.use_count() = " << gp2. use_count ( ) << '\n' ;
try {
Good not_so_good;
std:: shared_ptr< Good> gp1 = not_so_good. getptr ( ) ;
} catch ( std:: bad_weak_ptr& e) {
std:: cout << e. what ( ) << '\n' ;
}
std:: shared_ptr< Bad> bp1 = std:: make_shared< Bad> ( ) ;
std:: shared_ptr< Bad> bp2 = bp1-> getptr ( ) ;
std:: cout << "bp2.use_count() = " << bp2. use_count ( ) << '\n' ;
}