指针weak"/>
【16】c++11新特性 —>弱引用智能指针weak
定义
std::weak_ptr:
弱引用的智能指针,它不共享指针,不能操作资源,是用来监视 shared_ptr
中管理的资源是否存在。
use_count
#include <iostream>
#include <memory>
using namespace std;int main()
{shared_ptr<int>sp(new int);weak_ptr<int>wp1;wp1 = sp;cout << "use_count : " << wp1.use_count() << endl;cout << "use_count : " << sp.use_count() << endl;return 0;
}
expired()
通过调用std::weak_ptr类提供的expired()方法来判断观测的资源是否已经被释放.
#include <iostream>
#include <memory>
using namespace std;int main()
{shared_ptr<int>sp(new int);weak_ptr<int>wp(sp);cout << "1.wp " << (wp.expired() ? "is" : "is not ") << "expired" << endl;sp.reset();cout << "2.wp " << (wp.expired() ? "is" : "is not ") << "expired" << endl;return 0;
}
weak_ptr监测的就是shared_ptr管理的资源,当共享智能指针调用shared.reset();之后管理的资源被释放,因此weak.expired()函数的结果返回true,表示监测的资源已经不存在了。
lock
通过调用std::weak_ptr类提供的lock()方法来获取管理所监测资源的shared_ptr对象:
#include <iostream>
#include <memory>
using namespace std;int main()
{shared_ptr<int>sp(new int(10));shared_ptr<int>sp1;weak_ptr<int>wp(sp);sp1 = wp.lock(); //sp和sp1共享同一个资源cout << "sp1: use_count" << sp1.use_count() << endl;sp.reset();cout << "sp1:" << *sp1 << endl;return 0;
}
reset
通过调用std::weak_ptr类提供的reset()方法来清空对象,使其不监测任何资源
#include <iostream>
#include <memory>
using namespace std;int main()
{shared_ptr<int>sp(new int(10));shared_ptr<int>sp1;weak_ptr<int>wp(sp);sp1 = wp.lock(); //sp和sp1共享同一个资源cout << "sp1" << sp1.use_count() << endl;cout << "wp:" << wp.use_count() << endl;sp.reset();cout << "sp1:" << *sp1 << endl;wp.reset(); //清空对象cout << "wp:" << wp.use_count()<< endl;return 0;
}
更多推荐
【16】c++11新特性 —>弱引用智能指针weak
发布评论