C++ weak_ptr

2021. 3. 24. 10:48·C++/Library

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
'C++/Library' 카테고리의 다른 글
  • C++ STL 컨테이너 (STL Containers)
  • C++ 표준 템플릿 라이브러리 (STL, Standard Template Libraries)
  • C++ shared_ptr
  • C++ unique_ptr
Caniro
Caniro
  • Caniro
    Minimalism
    Caniro
  • 전체
    오늘
    어제
    • 분류 전체보기 (317)
      • Algorithm (13)
        • 알기 쉬운 알고리즘 (10)
        • Search (1)
        • Sort (2)
      • Arduino (0)
      • C++ (185)
        • Class (46)
        • Exception (6)
        • Library (51)
        • Overloading (10)
        • SmartPointer (5)
        • Syntax (33)
        • TBC++ (23)
        • Templates (9)
        • VisualStudio (2)
      • Embedded (1)
      • Git (4)
      • Java (5)
      • Linux (16)
        • Error (1)
        • Linux Structure (11)
      • MacOS (7)
      • OS (1)
        • Concurrency (1)
      • Python (21)
        • Class (1)
        • Function (2)
        • Syntax (17)
      • Raspberrypi (9)
      • Review (1)
      • Utility (12)
        • VSCode (5)
        • VirtualBox (3)
      • Web (8)
        • Nginx (1)
        • React (3)
        • Django (1)
      • Windows (20)
        • Registry (3)
        • WSL (1)
        • DeviceDriver (6)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    맥북 카카오톡 알림 안뜸
    citrix workspace
    SFC
    Windows 11
    시스템 복구
    java
    그림판
    제외
    윈도우 명령어
    mspaint
    MacOS
    스프링
    Workspace
    EXCLUDE
    알림
    logi options
    KakaoTalk
    스프링 프레임워크 핵심 기술
    unix
    windows
    dism
    백기선
    spring
    vscode
    윈도우
    로지텍 마우스 제스처
    SunOS 5.1
    Solaris 10
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Caniro
C++ weak_ptr
상단으로

티스토리툴바