C++ shared_ptr

2021. 3. 24. 10:47·C++/Library
목차
  1. shared_ptr
  2. 예제

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

  • 최근 글

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

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.