반응형
순환 의존성 문제 (Circular Dependency Issues)
순환 의존성
shared_ptr가 클래스 내부에서 계속 존재하게 되면, 인스턴스가 소멸자를 호출하지 못한다.만약 인스턴스 두 개가 멤버로 서로를
shared_ptr로 가지고 있다면, 마치 교착 상태처럼 소멸자를 둘 다 호출하지 못하는 상태가 된다.#include <iostream> #include <memory> class Person { std::string name_; std::shared_ptr<Person> partner_; public: Person(const std::string& name) : name_(name) { std::cout << name_ << " created\n"; } ~Person() { std::cout << name_ << " destroyed\n"; } friend bool partnerUp(std::shared_ptr<Person>& p1, std::shared_ptr<Person>& p2) { if (!p1 || !p2) return false; p1->partner_ = p2; p2->partner_ = p1; std::cout << p1->name_ << " is partnered with " << p2->name_ << '\n'; return true; } const std::string& getName() const { return name_; } }; int main() { auto lucy = std::make_shared<Person>("Lucy"); auto ricky = std::make_shared<Person>("Ricky"); partnerUp(lucy, ricky); } /* stdout stderr Lucy created Ricky created Lucy is partnered with Ricky */소멸자가 호출되지 않는 것을 볼 수 있다.
마지막 줄의
partnerUp(lucy, ricky);를 지우면 정상적으로 소멸자가 호출된다.weak_ptr로 해결할 수 있다.
반응형
'SW개발 > C++' 카테고리의 다른 글
| C++ 표준 템플릿 라이브러리 (STL, Standard Template Libraries) (0) | 2021.03.24 |
|---|---|
| 따라하며 배우는 C++ 16장 (0) | 2021.03.24 |
| C++ weak_ptr (0) | 2021.03.24 |
| C++ shared_ptr (0) | 2021.03.24 |
| C++ unique_ptr (0) | 2021.03.24 |