C++/Library
2021. 3. 24. 10:48
weak_ptr
weak_ptr
<memory>
라이브러리shared_ptr
의 순환 의존성 문제를 해결할 수 있다.#include <iostream> #include <memory> class Person { std::string name_; std::weak_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 Ricky destroyed Lucy destroyed */
mutex처럼
lock
이 걸린 상태에서만 개수를 세기 때문에, 인스턴스를 사용 중이 아니면 소멸자를 호출할 수 있는 원리이다.lock
함수를 사용하면shared_ptr
를 반환한다.#include <iostream> #include <memory> class Person { std::string name_; std::weak_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_; } const std::shared_ptr<Person> getPartner() const { return partner_.lock(); } }; int main() { auto lucy = std::make_shared<Person>("Lucy"); auto ricky = std::make_shared<Person>("Ricky"); partnerUp(lucy, ricky); std::cout << lucy->getName() << std::endl; std::cout << lucy->getPartner()->getName() << std::endl; } /* stdout stderr Lucy created Ricky created Lucy is partnered with Ricky Lucy Ricky Ricky destroyed Lucy destroyed */
'C++ > Library' 카테고리의 다른 글
C++ STL 컨테이너 (STL Containers) (0) | 2021.03.24 |
---|---|
C++ 표준 템플릿 라이브러리 (STL, Standard Template Libraries) (0) | 2021.03.24 |
C++ shared_ptr (0) | 2021.03.24 |
C++ unique_ptr (0) | 2021.03.24 |
C++ std::move (0) | 2021.03.24 |