C++ shared_ptr

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

shared_ptr

shared_ptr

  • <memory> 라이브러리

  • 몇 개의 변수가 포인터를 참조하고 있는지 내부적으로 계산한다.


예제

main.cpp

  #include <iostream>
  #include <memory>
  #include "Resource.h"

  int            main()
  {
    Resource* res = new Resource(3);
    res->setAll(1);

    {
      std::shared_ptr<Resource> ptr1(res);

      ptr1->print();

      {
        std::shared_ptr<Resource> ptr2(ptr1);

        ptr2->setAll(3);
        ptr2->print();

        std::cout << "Going out of the block\n";
      }

      ptr1->print();
      std::cout << "Going out of the outer block\n";
    }
    std::cout << "Last of main function\n";
  }

  /* stdout stderr
  Resource length constructed
  1 1 1
  3 3 3
  Going out of the block
  3 3 3
  Going out of the outer block
  Resource destoryed
  Last of main function
  */

Resource.h

  #pragma once

  #include <iostream>

  class Resource
  {
  public:
    int    *data_ = nullptr;
    unsigned length_ = 0;

    Resource()
    {
      std::cout << "Resource default constructed\n";
    }

    Resource(unsigned length)
    {
      std::cout << "Resource length constructed\n";
      init(length);
    }

    Resource(const Resource& res)
    {
      std::cout << "Resource copy constructed\n";
      init(res.length_);
      for (unsigned i = 0; i < length_; ++i)
        data_[i] = res.data_[i];
    }

    ~Resource()
    {
      std::cout << "Resource destoryed\n";

      if (data_ != nullptr) delete[] data_;
    }

    void    init(unsigned length)
    {
      data_ = new int[length];
      length_ = length;
    }

    Resource& operator = (Resource& res)
    {
      std::cout << "Resource copy assignment\n";
      if (&res == this) return *this;

      if (data_ != nullptr) delete[] data_;
      init(res.length_);
      for (unsigned i = 0; i < length_; ++i)
        data_[i] = res.data_[i];
      return *this;
    }

    void    print()
    {
      for (unsigned i = 0; i < length_; ++i)
        std::cout << data_[i] << ' ';
      std::cout << std::endl;
    }

    void    setAll(const int& v)
    {
      for (unsigned i = 0; i < length_; ++i)
        data_[i] = v;
    }
  };
  • 아래와 같이 ptr2를 생성하면 ptr1에서 알 수 없기 때문에 에러가 발생한다.

    std::shared_ptr<Resource> ptr2(res);
  • make_shared를 사용해서 직접 초기화하는 방법이 일반적이다.

    main.cpp

    #include <iostream>
    #include <memory>
    #include "Resource.h"
    
    int            main()
    {
      {
        auto ptr1 = std::make_shared<Resource>(3);
        ptr1->setAll(1);
        ptr1->print();
    
        {
          auto ptr2 = ptr1;
    
          ptr2->setAll(3);
          ptr2->print();
    
          std::cout << "Going out of the block\n";
        }
    
        ptr1->print();
        std::cout << "Going out of the outer block\n";
      }
      std::cout << "Last of main function\n";
    }
    
    /* stdout stderr
    Resource length constructed
    1 1 1
    3 3 3
    Going out of the block
    3 3 3
    Going out of the outer block
    Resource destoryed
    Last of main function
    */

저작자표시 (새창열림)

'C++ > Library' 카테고리의 다른 글

C++ 표준 템플릿 라이브러리 (STL, Standard Template Libraries)  (0) 2021.03.24
C++ weak_ptr  (0) 2021.03.24
C++ unique_ptr  (0) 2021.03.24
C++ std::move  (0) 2021.03.24
C++ 출력 스트림 끊기  (0) 2021.03.24
'C++/Library' 카테고리의 다른 글
  • C++ 표준 템플릿 라이브러리 (STL, Standard Template Libraries)
  • C++ weak_ptr
  • C++ unique_ptr
  • C++ std::move
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)
  • 블로그 메뉴

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

  • 공지사항

  • 인기 글

  • 태그

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

  • 최근 글

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

티스토리툴바