shared_ptr의 순환참조 문제가 있어 다른 유형의 스마트 포인터인 weak_ptr은 객체의 참조 카운트에 영향을 주지 않아 순환 참조를 끊는데 유용하다.
#include <iostream>
#include <memory>
class A;
class B
{
public:
std::weak_ptr<A> aPtr; // A 클래스에 대한 weak_ptr
~B() { std::cout << "B destroyed\n"; }
};
class A
{
public:
std::shared_ptr<B> bPtr; // B 클래스에 대한 shared_ptr
~A() { std::cout << "A destroyed\n"; }
};
int main()
{
// A와 B 객체를 각각 생성
std::shared_ptr<A> a = std::make_shared<A>();
std::shared_ptr<B> b = std::make_shared<B>();
// A와 B가 서로를 참조하되, B는 A에 대해 weak_ptr을 사용하여 순환 참조를 방지
a->bPtr = b;
b->aPtr = a;
// 이제 A와 B는 서로를 참조하지만 순환 참조가 발생하지 않음
// B는 A에 대해 weak_ptr을 사용하므로 참조 카운트에 영향을 주지 않음
return 0;
}'C, C++' 카테고리의 다른 글
| <atomic> (0) | 2024.02.21 |
|---|---|
| <thread> (0) | 2024.02.20 |
| shared_ptr (0) | 2023.07.16 |
| unique_ptr (0) | 2023.07.15 |
| <unordered_map>, <unordered_set> (0) | 2023.07.11 |