std::weak_ptr
#include <iostream>
#include <memory>
class A;
class B;
class A {
public:
std::shared_ptr<B> pointer;
~A() {
std::cout << "A 被銷燬" << std::endl;
}
};
class B {
public:
std::shared_ptr<A> pointer;
~B() {
std::cout << "B 被銷燬" << std::endl;
}
};
int main() {
std::shared_ptr<A> a = std::make_shared<A>();
std::shared_ptr<B> b = std::make_shared<B>();
a->pointer = b;
b->pointer = a;
return 0;
}
以上代碼中shared_ptr存在着資源無法釋放的問題,因爲a,b內部的pointer同時又引用了b,a,這使得a,b的引用計數變爲了2,而離開作用域時,a,b智能指針被析構,引用計數減一,導致了a,b對象指向的內存區域引用計數不爲0,而外部已經無法找到這塊區域了,因此造成了內存泄漏。
解決方法爲使用std::weak_ptr,這是一種弱引用,不會引起引用計數增加,
#include <iostream>
#include <memory>
class A;
class B;
class A {
public:
// A 或 B 中至少有一個使用 weak_ptr
std::weak_ptr<B> pointer;
~A() {
std::cout << "A 被銷燬" << std::endl;
}
};
class B {
public:
std::shared_ptr<A> pointer;
~B() {
std::cout << "B 被銷燬" << std::endl;
}
};
int main() {
std::shared_ptr<A> a = std::make_shared<A>();
std::shared_ptr<B> b = std::make_shared<B>();
a->pointer = b;
b->pointer = a;
return 0;
}
結果:
B 被銷燬
A 被銷燬