弱类型指针
- weak_ptr 称为弱引用,没有所有权,不能调用 -> 和 *
- 不能单独存在
- weak_ptr 可以通过 lock() 函数来提升为 shared_ptr(类型转换)
使用场景:一个 类 要存储其他 这个类 的信息是,如果使用的是 shared_ptr,那么在销毁时会遇到 循环依赖问题(Cyclic dependency problem),所以使用一个不需要所有权的指针进行标记同类对象。
测试代码:
#include <iostream>
#include <memory>
class Stu {
std::string m_name;
std::shared_ptr<Stu> stuFriend;
//std::weak_ptr<Stu> stuFriend;
public:
Stu() {
this->m_name = "stuTemp";
std::cout << "无参构造" << std::endl;
}
Stu(std::string name) :m_name(name) {
std::cout << "有参构造" << std::endl;
}
~Stu() {
std::cout << "析构" << std::endl;
}
void printStuName() const {
std::cout << this->m_name << std::endl;
}
void setStuName(std::string name) {
this->m_name = name;
}
void setStuFriend(std::shared_ptr<Stu> s_p) {
stuFriend = s_p;
}
};
int main() {
std::shared_ptr<Stu> s_p1 = std::make_shared<Stu>("AA"); // 需要析构
std::weak_ptr<Stu> w_p1(s_p1); // weak_ptr
// use_count()
std::cout << s_p1.use_count() << std::endl; // 1
std::cout << w_p1.use_count() << std::endl; // 1 可以调用但是不会 + 1
// lock()
std::shared_ptr<Stu> s_p2 = w_p1.lock();
std::cout << s_p1.use_count() << std::endl; // 2
std::cout << w_p1.use_count() << std::endl; // 2
std::cout << s_p2.use_count() << std::endl; // 2
// ...
std::shared_ptr<Stu> s_p3 = std::make_shared<Stu>("S3");
std::shared_ptr<Stu> s_p4 = std::make_shared<Stu>("S4");
// 循环依赖问题
s_p3->setStuFriend(s_p4); // 没有析构
s_p4->setStuFriend(s_p3); // 没有析构
return 0;
}
运行结果:
会发现析构少了 s_p3 和 s_p4 的。这里就是因为循环依赖的问题,需要使用没有所有权的指针 weak_ptr
修改后测试:
#include <iostream>
#include <memory>
class Stu {
std::string m_name;
//std::shared_ptr<Stu> stuFriend;
std::weak_ptr<Stu> stuFriend;
public:
Stu() {
this->m_name = "stuTemp";
std::cout << "无参构造" << std::endl;
}
Stu(std::string name) :m_name(name) {
std::cout << "有参构造" << std::endl;
}
~Stu() {
std::cout << "析构" << std::endl;
}
void printStuName() const {
std::cout << this->m_name << std::endl;
}
void setStuName(std::string name) {
this->m_name = name;
}
void setStuFriend(std::shared_ptr<Stu> s_p) {
stuFriend = s_p;
}
};
int main() {
std::shared_ptr<Stu> s_p1 = std::make_shared<Stu>("AA"); // 需要析构
std::weak_ptr<Stu> w_p1(s_p1); // weak_ptr
// use_count()
std::cout << s_p1.use_count() << std::endl; // 1
std::cout << w_p1.use_count() << std::endl; // 1 可以调用但是不会 + 1
// lock()
std::shared_ptr<Stu> s_p2 = w_p1.lock();
std::cout << s_p1.use_count() << std::endl; // 2
std::cout << w_p1.use_count() << std::endl; // 2
std::cout << s_p2.use_count() << std::endl; // 2
// ...
std::shared_ptr<Stu> s_p3 = std::make_shared<Stu>("S3");
std::shared_ptr<Stu> s_p4 = std::make_shared<Stu>("S4");
// 循环依赖问题
s_p3->setStuFriend(s_p4);
s_p4->setStuFriend(s_p3);
return 0;
}
运行结果: