需求:
有三个类,分别是A,B, R。在B类里new 了一个R的智能指针, 这个R的生命周期和B相同。同时A类也存了一个B中存放关于R的智能指针。B销毁同时A指向R的指针也失效,并调用R的析构函数,如何实现
#include <iostream>
#include <memory>
class R {
public:
~R() {
std::cout << "R's destructor called" << std::endl;
}
};
class B {
public:
std::shared_ptr<R> r_ptr;
B() {
r_ptr = std::make_shared<R>();
}
};
class A {
public:
std::weak_ptr<R> r_weak_ptr;
void setRPtr(const std::shared_ptr<R>& r_ptr) {
r_weak_ptr = r_ptr;
}
void useRPtr() {
std::shared_ptr<R> r_shared_ptr = r_weak_ptr.lock();
if (r_shared_ptr) {
// 使用r_shared_ptr
std::cout << "Using R through A" << std::endl;
} else {
std::cout << "R has been destroyed" << std::endl;
}
}
};
int main() {
{
A a;
{
B b;
a.setRPtr(b.r_ptr);
a.useRPtr(); // 输出: Using R through A
} // B对象在这里被销毁,R的引用计数减为0,R的析构函数被调用
a.useRPtr(); // 输出: R has been destroyed
}
return 0;
}