面试题答案
一键面试#include <iostream>
#include <memory>
class B;
class A {
public:
std::weak_ptr<B> b_ptr;
~A() {
std::cout << "A destroyed" << std::endl;
}
};
class B {
public:
std::shared_ptr<A> a_ptr;
~B() {
std::cout << "B destroyed" << std::endl;
}
};
int main() {
std::shared_ptr<A> a = std::make_shared<A>();
std::shared_ptr<B> b = std::make_shared<B>();
a->b_ptr = b;
b->a_ptr = a;
return 0;
}
在这个代码示例中,std::weak_ptr
起到的作用是:它是一种弱引用,不会增加对象的引用计数。在A
类中使用std::weak_ptr<B>
来指向B
类对象,这样当A
和B
对象互相引用时,std::weak_ptr
不会像std::shared_ptr
那样增加引用计数,从而打破了循环引用。当A
和B
对象的其他std::shared_ptr
都被销毁后,这两个对象就可以正常析构,避免了内存泄漏。