weak_ptr的接口如下表
由表可知,它并没有重载*和->等运算符,所以,它不能像shared_ptr和unique_ptr一样单独使用,它只能和share_ptr搭配使用。
借助 weak_ptr 类型指针, 我们可以获取 shared_ptr 指针的一些状态信息,比如有多少指向相同的 shared_ptr 指针、shared_ptr 指针指向的堆内存是否已经被释放等等。
注意:当 weak_ptr 类型指针的指向和某一 shared_ptr 指针相同时,weak_ptr 指针并不会使所指堆内存的引用计数加 1;同样,当 weak_ptr 指针被释放时,之前所指堆内存的引用计数也不会因此而减 1。也就是说,weak_ptr 类型指针并不会影响所指堆内存空间的引用计数。
通过一个示例来说明它的使用:
#include <iostream>
#include <memory>
using namespace std;
int main()
{
std::shared_ptr<int> sp1(new int(10));
std::shared_ptr<int> sp2(sp1);
std::weak_ptr<int> wp(sp2);
//输出和 wp 同指向的 shared_ptr 类型指针的数量
cout << wp.use_count() << endl;
//释放 sp2
sp2.reset();
cout << wp.use_count() << endl;
//借助 lock() 函数,返回一个和 wp 同指向的 shared_ptr 类型指针,获取其存储的数据
cout << *(wp.lock()) << endl;
return 0;
}
输出结果:
2
1
10
示例2
std::shared_ptr<int> sp(new int(1));
std::cout << sp.use_count() << std::endl;
std::weak_ptr<int> wp(sp);
std::cout << sp.use_count() << std::endl;
std::shared_ptr<int> sp1 = wp.lock();
std::cout << sp1.use_count() << std::endl;
输出结果
1
1
2
如果感觉对您有帮助,帮忙点个赞哟!