SlideShare uma empresa Scribd logo
1 de 9
c++정리-스마트포인터




c++정리-스마트포인터




                        박철희
1.스마트 포인터 정의 및 역활                           c++정리-스마트포인터

1. 정의:임의의 객체가 다른 타입의 포인터 역할을 하는것.

2. 장점:
   멤버 객체를 둘러싸고 있는 객체 이다.
   즉, 생성/복사/대입/소멸의 모든 과정을 사용자가 제어 할 수 있다.
   대표적 활용이 소멸자에서의 멤버 객체 자동 삭제 이다.

3. 역할
   a. 멤버 객체를 소멸자에서 자동으로 delete한다.

  b. 스마트 포인터 객체로 멤버 객체에 접근 할 수 있다.

  c. 모든 type에 대해서 스마트 포인터를 사용 할 수 있다.

  d. 얕은 복사 문제를 해결할 수 있다.
a. 멤버 객체를 소멸자에서 자동으로 delete한다.                                        c++정리-스마트포인터


  class Car
  {
  public:
                void Go() { cout << "Car Go" << endl; }
  };

  class ptr
  {
                Car* obj;
  public:
                ptr( Car* p = 0 ) : obj(p) {} //생성자에서 p를 obj로 넣어준다.

                  //ptr이 객체이기 때문에 함수를 벗어날때 소멸자를 불러준다.
                  //그래서 생성한 obj를 delete하는 code를 넣어주면 사용자가 따로 obj를 delete하는
               // code를 넣을 필요가 없다.
                  ~ptr() { delete obj; }
  }


  int main()
  {
                ptr p = new Car; // ptr p( new Car ) 와 같다.
  }
b. 스마트 포인터 객체로 멤버 객체에 접근 할 수 있다.                                             c++정리-스마트포인터


  class Car
  {
  public:
                void Go() { cout << "Car Go" << endl; }
  };

  class ptr
  {
                Car* obj;
  public:
                ptr( Car* p = 0 ) : obj(p) {} //생성자에서 p를 obj로 copy한다.
                ~ptr() { delete obj; }
               Car* operator->() { return obj; }  객체 멤버에 접근하기 위한 ‘->’ 재정의
                Car& operator*() { return *obj; }  객체 멤버에 접근하기 위한 ‘*’ 재정의
  }

  int main()
  {
                ptr p = new Car; // ptr p( new Car )

                 p->Go();//OK Car의 go 호출        p->  p.operator->() 호출.
               (*p).GO(); //OK Car의 go 호출       *p  p.operator*() 호출.
  }
c. 모든 type에 대해서 스마트 포인터를 사용 할 수 있다.                               c++정리-스마트포인터

 template으로 만들어야 한다.

 template<typename T> class ptr  typename T에 대한 스마트 포인터를 사용할 수 있다.
 {
            T* obj;
 public:
            ptr( T* p = 0 ) : obj(p) {}
           생성자에서 type T의 객체를 obj로 복사

         ~ptr() { delete obj; }
         소멸자에서 자동으로 obj 삭제

        T* operator->() { return obj; }
        T& operator*() { return *obj; }
       type T의 객체에 접근 하기 위한 연산자 재정의
 };
d. 얕은 복사 문제를 해결할 수 있다.                                                                                        c++정리-스마트포인터
1)소유권 이전 방법 사용
template<typename T> class ptr
{
               T* obj;
public:
               ptr( ptr& p ) : obj(p.obj) //먼저 얕은 복사를 하고.
               {
                      p.obj = 0; // 기존 포인터는 reset 한다.(이전 스마트 포인터의 소유권을 포기한다.)
               }
               ptr( T* p = 0 ) : obj(p) {} //생성자
               ~ptr() { delete obj; }     //소멸자
               T* operator->() { return obj; } //연산자 재정의
               T& operator*() { return *obj; }
};

int main()
{
             ptr<int> p1 = new int;
             *p1 = 10;
             ptr<int> p2 = p1; // 이 순간 공유가 아니라 p2로 자원이 전달됩니다.

             cout << *p1 << endl; // 1.. runtime error..
             cout << *p2 << endl; // 2. ok..
}
                                                           Cf. c++ 표준 library(STL)에는 소유권 이전 스마트 포인터인 auto_prt<> 이 있다.
                                                           int main()
                                                           {
                                                                          auto_ptr<int> p1( new int );
                                                                          *p1 = 10;

                                                                      auto_ptr<int> p2(p1); // 소유권 이전

                                                                      cout << *p1 << endl; // runtime error
                                                                      cout << *p2 << endl; // 10
                                                           }
d. 얕은 복사 문제를 해결할 수 있다.                                                                                       c++정리-스마트포인터

2)참조 계수 기반의 스마트 포인터
template<typename T> class ptr                                 int main()
{                                                              {
               T* obj;                                                        ptr<int> p1 = new int;
               int* ref; // 참조계수를 위한 변수
public:                                                                       *p1 = 10;
               ptr( T* p = 0 ) : obj(p)
               {                                                              ptr<int> p2 = p1;
                    ref = new int(1); //생성자에서 참조 계수 생성.
               }                                                              cout << *p1 << endl; //ok 10
                                                                              cout << *p2 << endl; //ok 10
             //참조계수로 구현한 복사 생성자                                }
             ptr( const ptr& p ) : obj(p.obj), ref(p.ref)
             {
                   ++(*ref);
             }

             //소멸자
             ~ptr()
             {                                                     Cf. c++ 표준 library(STL)에는 참조 계수 기반의 스마트 포인터인
                if ( --(*ref) == 0 ) //ref가 0일 경우만 객체 delete           shared_ptr<> 가 있다.
                {                                                  int main()
                       delete obj;                                 {
                       delete ref;                                     shared_ptr<int> p1( new int);
                 }                                                     *p1 = 10;
             }                                                         shared_ptr<int> p2(p1);//p1의 멤버가 p2로 copy되면서 참조계수 1증가.
                                                                       cout << *p1 << endl; //ok 10
                                                                       cout << *p2 << endl; //ok 10
             T* operator->() { return obj; }                       }
             T& operator*() { return *obj; }
};
d. 얕은 복사 문제를 해결할 수 있다.                                                                                        c++정리-스마트포인터

3) 객체 내부에 참조계수를 관리하자.
   스마트 포인터의 생성자,소멸자에서 객체 내부의 incstrong,decstrong을 호출하게 하자.

객체 내부에 mCount 참조계수 관리                                           스마트 포인터의 생성자,소멸자에서 객체 내부의 incstrong,decstrong을 호출 함
class Car
{                                                               template<typename T> class sp
    int mCount; //참조 계수                                         {
public:                                                                        T* m_ptr;
                                                                public:
      Car() : mCount(0) {}//생성자
     void incStrong() { ++mCount; }                                             //생성자
     void decStrong()                                                           sp( T* other = 0 ) : m_ptr(other)
     {                                                                          {
         if ( --mCount == 0 ) delete this;   // 자신을 스스로 파괴 함.                       if ( m_ptr ) m_ptr->incStrong(); //객체의 incStrong 호출
     }                                                                          }
};
                                                                                //복사생성자
                                                                                sp( const sp& p ) : m_ptr( p.m_ptr )
                                                                                {
                                                                                      if ( m_ptr ) m_ptr->incStrong(); //객체의 incStrong 호출
                                                                                }
 int main()
 {                                                                              //소멸자
                                                                                ~sp()
       sp<Car> p1 = new Car;// 생성자에서 incStrong 부름.                          {
                                                                                   if ( m_ptr ) m_ptr->decStrong(); //객체의 decStrong 호출
       sp<Car> p2 = p1;                                                     }
        //복사생성자에서 incStrong 부름. p2=new Car(p1); 와 같음.           };
       sp<int> p3 = new int; //error
       int class에서 incStrong , decStrong 이 없다.
         그래서, 안드로이드에서는 최상위 부모 class인 Refbase에
         incStrong, decStrong 을 정의해 놓고 상속받아서 사용하게 되어있다.

 }
안드로이드에서의 스마트 포인터 사용 예                                                                               c++정리-스마트포인터

-안드로이드에서는 Strongpointer 객체로 스마트 포인터 기능을 구현한다.
 또한, 최상위 class인 Refbase에 참조계수가 정의 되어 있다.(incStrong, decStrong )

StrongPointer.h                                           //소멸자 정의
template <typename T>                                     sp<T>::~sp()
class sp                                                  {
{                                                            if (m_ptr) m_ptr->decStrong(this);
public:                                                   }

  sp(T* other); //생성자 선언                                  결론적으로 안드로이드에서는 최상위 class인 Refbas의
  sp(const sp<T>& other); //복사 생성자 선언                      incStrong,decStrong이 불리게 된다.
  ~sp(); //소멸자 선언

  //연산자 재정의                                               Refbase.h
  inline T& operator* () const { return *m_ptr; }         class RefBase
  inline T* operator-> () const { return m_ptr; }         {
  inline T* get() const     { return m_ptr; }             public:
                                                                  void       incStrong(const void* id) const;
private:                                                          void       decStrong(const void* id) const;
  T* m_ptr;                                                        …
                                                          }
}
//생성자 정의
template<typename T>                                      Refbase.cpp
sp<T>::sp(T* other)                                       void RefBase::incStrong(const void* id) const
: m_ptr(other)                                            {
  {                                                           //참조 계수 값 증가
    if (other) other->incStrong(this); T의 incStrong 호출      const int32_t c = android_atomic_inc(&refs->mStrong);
  }                                                       }
//복사생성자 정의
template<typename T>                                      void RefBase::decStrong(const void* id) const
sp<T>::sp(const sp<T>& other)                             {
: m_ptr(other.m_ptr)                                         //참조 계수 값 감소
  {                                                           const int32_t c = android_atomic_dec(&refs->mStrong);
    if (m_ptr) m_ptr->incStrong(this);                    }
  }

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Memory allocation in c
Memory allocation in cMemory allocation in c
Memory allocation in c
 
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptxUnit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 forms
 
Asp.net basic
Asp.net basicAsp.net basic
Asp.net basic
 
Optional in Java 8
Optional in Java 8Optional in Java 8
Optional in Java 8
 
Dynamic Memory allocation
Dynamic Memory allocationDynamic Memory allocation
Dynamic Memory allocation
 
Event handling
Event handlingEvent handling
Event handling
 
Angular Directives
Angular DirectivesAngular Directives
Angular Directives
 
Angular Dependency Injection
Angular Dependency InjectionAngular Dependency Injection
Angular Dependency Injection
 
The Functional Programmer's Toolkit (NDC London 2019)
The Functional Programmer's Toolkit (NDC London 2019)The Functional Programmer's Toolkit (NDC London 2019)
The Functional Programmer's Toolkit (NDC London 2019)
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
 
Spring boot - an introduction
Spring boot - an introductionSpring boot - an introduction
Spring boot - an introduction
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event Handling
 
Location-Based Services on Android
Location-Based Services on AndroidLocation-Based Services on Android
Location-Based Services on Android
 
Async/Await
Async/AwaitAsync/Await
Async/Await
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressions
 
GMock framework
GMock frameworkGMock framework
GMock framework
 
Android datastorage
Android datastorageAndroid datastorage
Android datastorage
 
Virtual machine and javascript engine
Virtual machine and javascript engineVirtual machine and javascript engine
Virtual machine and javascript engine
 
Introduction to JSON
Introduction to JSONIntroduction to JSON
Introduction to JSON
 

Destaque

Stagefright recorder part1
Stagefright recorder part1Stagefright recorder part1
Stagefright recorder part1fefe7270
 
Camera camcorder framework overview(ginger bread)
Camera camcorder framework overview(ginger bread)Camera camcorder framework overview(ginger bread)
Camera camcorder framework overview(ginger bread)fefe7270
 
Modern effective c++ 항목 3
Modern effective c++ 항목 3Modern effective c++ 항목 3
Modern effective c++ 항목 3ssuser7c5a40
 
Effective Modern C++ MVA item 18 Use std::unique_ptr for exclusive-ownership ...
Effective Modern C++ MVA item 18 Use std::unique_ptr for exclusive-ownership ...Effective Modern C++ MVA item 18 Use std::unique_ptr for exclusive-ownership ...
Effective Modern C++ MVA item 18 Use std::unique_ptr for exclusive-ownership ...Seok-joon Yun
 
TCP가 실패하는 상황들
TCP가 실패하는 상황들TCP가 실패하는 상황들
TCP가 실패하는 상황들ssuser7c5a40
 
Effective c++ 정리 chapter 4
Effective c++ 정리 chapter 4Effective c++ 정리 chapter 4
Effective c++ 정리 chapter 4연우 김
 
Effective c++ 2
Effective c++ 2Effective c++ 2
Effective c++ 2현찬 양
 
Effective C++ 정리 chapter 3
Effective C++ 정리 chapter 3Effective C++ 정리 chapter 3
Effective C++ 정리 chapter 3연우 김
 
C++ 11 에 대해서 쉽게 알아봅시다 1부
C++ 11 에 대해서 쉽게 알아봅시다 1부C++ 11 에 대해서 쉽게 알아봅시다 1부
C++ 11 에 대해서 쉽게 알아봅시다 1부Gwangwhi Mah
 
Surface flingerservice(서피스 상태 변경 jb)
Surface flingerservice(서피스 상태 변경 jb)Surface flingerservice(서피스 상태 변경 jb)
Surface flingerservice(서피스 상태 변경 jb)fefe7270
 
실전프로젝트 정서경 양현찬
실전프로젝트 정서경 양현찬실전프로젝트 정서경 양현찬
실전프로젝트 정서경 양현찬현찬 양
 
GPG 1.2 템플릿 메타프로그래밍을 이용한 빠른 수학 연산
GPG 1.2 템플릿 메타프로그래밍을 이용한 빠른 수학 연산GPG 1.2 템플릿 메타프로그래밍을 이용한 빠른 수학 연산
GPG 1.2 템플릿 메타프로그래밍을 이용한 빠른 수학 연산Taeung Ra
 
NDC14 - 사례로 배우는 디스어셈블리 디버깅
NDC14 - 사례로 배우는 디스어셈블리 디버깅NDC14 - 사례로 배우는 디스어셈블리 디버깅
NDC14 - 사례로 배우는 디스어셈블리 디버깅Seungjae Lee
 
Effective c++chapter1 and2
Effective c++chapter1 and2Effective c++chapter1 and2
Effective c++chapter1 and2성연 김
 
Modern C++ 프로그래머를 위한 CPP11/14 핵심
Modern C++ 프로그래머를 위한 CPP11/14 핵심Modern C++ 프로그래머를 위한 CPP11/14 핵심
Modern C++ 프로그래머를 위한 CPP11/14 핵심흥배 최
 
[0119 박민근] 기술 면접시 자주 나오는 문제들(ver 2013)
[0119 박민근] 기술 면접시 자주 나오는 문제들(ver 2013)[0119 박민근] 기술 면접시 자주 나오는 문제들(ver 2013)
[0119 박민근] 기술 면접시 자주 나오는 문제들(ver 2013)MinGeun Park
 
객체지향 개념 (쫌 아는체 하기)
객체지향 개념 (쫌 아는체 하기)객체지향 개념 (쫌 아는체 하기)
객체지향 개념 (쫌 아는체 하기)Seung-June Lee
 

Destaque (19)

Stagefright recorder part1
Stagefright recorder part1Stagefright recorder part1
Stagefright recorder part1
 
Camera camcorder framework overview(ginger bread)
Camera camcorder framework overview(ginger bread)Camera camcorder framework overview(ginger bread)
Camera camcorder framework overview(ginger bread)
 
Modern effective cpp 항목1
Modern effective cpp 항목1Modern effective cpp 항목1
Modern effective cpp 항목1
 
Modern effective c++ 항목 3
Modern effective c++ 항목 3Modern effective c++ 항목 3
Modern effective c++ 항목 3
 
Effective Modern C++ MVA item 18 Use std::unique_ptr for exclusive-ownership ...
Effective Modern C++ MVA item 18 Use std::unique_ptr for exclusive-ownership ...Effective Modern C++ MVA item 18 Use std::unique_ptr for exclusive-ownership ...
Effective Modern C++ MVA item 18 Use std::unique_ptr for exclusive-ownership ...
 
TCP가 실패하는 상황들
TCP가 실패하는 상황들TCP가 실패하는 상황들
TCP가 실패하는 상황들
 
Effective c++ 정리 chapter 4
Effective c++ 정리 chapter 4Effective c++ 정리 chapter 4
Effective c++ 정리 chapter 4
 
Effective c++ 2
Effective c++ 2Effective c++ 2
Effective c++ 2
 
Effective C++ 정리 chapter 3
Effective C++ 정리 chapter 3Effective C++ 정리 chapter 3
Effective C++ 정리 chapter 3
 
Titanic with r
Titanic with rTitanic with r
Titanic with r
 
C++ 11 에 대해서 쉽게 알아봅시다 1부
C++ 11 에 대해서 쉽게 알아봅시다 1부C++ 11 에 대해서 쉽게 알아봅시다 1부
C++ 11 에 대해서 쉽게 알아봅시다 1부
 
Surface flingerservice(서피스 상태 변경 jb)
Surface flingerservice(서피스 상태 변경 jb)Surface flingerservice(서피스 상태 변경 jb)
Surface flingerservice(서피스 상태 변경 jb)
 
실전프로젝트 정서경 양현찬
실전프로젝트 정서경 양현찬실전프로젝트 정서경 양현찬
실전프로젝트 정서경 양현찬
 
GPG 1.2 템플릿 메타프로그래밍을 이용한 빠른 수학 연산
GPG 1.2 템플릿 메타프로그래밍을 이용한 빠른 수학 연산GPG 1.2 템플릿 메타프로그래밍을 이용한 빠른 수학 연산
GPG 1.2 템플릿 메타프로그래밍을 이용한 빠른 수학 연산
 
NDC14 - 사례로 배우는 디스어셈블리 디버깅
NDC14 - 사례로 배우는 디스어셈블리 디버깅NDC14 - 사례로 배우는 디스어셈블리 디버깅
NDC14 - 사례로 배우는 디스어셈블리 디버깅
 
Effective c++chapter1 and2
Effective c++chapter1 and2Effective c++chapter1 and2
Effective c++chapter1 and2
 
Modern C++ 프로그래머를 위한 CPP11/14 핵심
Modern C++ 프로그래머를 위한 CPP11/14 핵심Modern C++ 프로그래머를 위한 CPP11/14 핵심
Modern C++ 프로그래머를 위한 CPP11/14 핵심
 
[0119 박민근] 기술 면접시 자주 나오는 문제들(ver 2013)
[0119 박민근] 기술 면접시 자주 나오는 문제들(ver 2013)[0119 박민근] 기술 면접시 자주 나오는 문제들(ver 2013)
[0119 박민근] 기술 면접시 자주 나오는 문제들(ver 2013)
 
객체지향 개념 (쫌 아는체 하기)
객체지향 개념 (쫌 아는체 하기)객체지향 개념 (쫌 아는체 하기)
객체지향 개념 (쫌 아는체 하기)
 

Semelhante a C++정리 스마트포인터

Cpp 0x kimRyungee
Cpp 0x kimRyungeeCpp 0x kimRyungee
Cpp 0x kimRyungeescor7910
 
Boost라이브러리의내부구조 20151111 서진택
Boost라이브러리의내부구조 20151111 서진택Boost라이브러리의내부구조 20151111 서진택
Boost라이브러리의내부구조 20151111 서진택JinTaek Seo
 
2012 Ds D2 03
2012 Ds D2 032012 Ds D2 03
2012 Ds D2 03chl132435
 
2012 Ds D2 03 Pdf
2012 Ds D2 03 Pdf2012 Ds D2 03 Pdf
2012 Ds D2 03 Pdfkd19h
 
More effective c++ chapter1 2_dcshin
More effective c++ chapter1 2_dcshinMore effective c++ chapter1 2_dcshin
More effective c++ chapter1 2_dcshinDong Chan Shin
 
Visual studio 2010
Visual studio 2010Visual studio 2010
Visual studio 2010MinGeun Park
 
C++ Advanced 강의 2주차
C++ Advanced 강의 2주차C++ Advanced 강의 2주차
C++ Advanced 강의 2주차HyunJoon Park
 
파이썬 스터디 9장
파이썬 스터디 9장파이썬 스터디 9장
파이썬 스터디 9장SeongHyun Ahn
 
[NDC2016] TERA 서버의 Modern C++ 활용기
[NDC2016] TERA 서버의 Modern C++ 활용기[NDC2016] TERA 서버의 Modern C++ 활용기
[NDC2016] TERA 서버의 Modern C++ 활용기Sang Heon Lee
 
포인터의기초 (2) - 포인터 사용하기1
포인터의기초 (2) - 포인터 사용하기1포인터의기초 (2) - 포인터 사용하기1
포인터의기초 (2) - 포인터 사용하기1Hoyoung Jung
 
14장 - 15장 예외처리, 템플릿
14장 - 15장 예외처리, 템플릿14장 - 15장 예외처리, 템플릿
14장 - 15장 예외처리, 템플릿유석 남
 
[C++ Korea 2nd Seminar] C++17 Key Features Summary
[C++ Korea 2nd Seminar] C++17 Key Features Summary[C++ Korea 2nd Seminar] C++17 Key Features Summary
[C++ Korea 2nd Seminar] C++17 Key Features SummaryChris Ohk
 
Modern C++의 타입 추론과 람다, 컨셉
Modern C++의 타입 추론과 람다, 컨셉Modern C++의 타입 추론과 람다, 컨셉
Modern C++의 타입 추론과 람다, 컨셉HyunJoon Park
 
RNC C++ lecture_2 operator, if
RNC C++ lecture_2 operator, ifRNC C++ lecture_2 operator, if
RNC C++ lecture_2 operator, ifitlockit
 
RNC C++ lecture_4 While, For
RNC C++ lecture_4 While, ForRNC C++ lecture_4 While, For
RNC C++ lecture_4 While, Foritlockit
 

Semelhante a C++정리 스마트포인터 (20)

Cpp 0x kimRyungee
Cpp 0x kimRyungeeCpp 0x kimRyungee
Cpp 0x kimRyungee
 
Boost라이브러리의내부구조 20151111 서진택
Boost라이브러리의내부구조 20151111 서진택Boost라이브러리의내부구조 20151111 서진택
Boost라이브러리의내부구조 20151111 서진택
 
2012 Ds D2 03
2012 Ds D2 032012 Ds D2 03
2012 Ds D2 03
 
2012 Ds D2 03 Pdf
2012 Ds D2 03 Pdf2012 Ds D2 03 Pdf
2012 Ds D2 03 Pdf
 
More effective c++ chapter1 2_dcshin
More effective c++ chapter1 2_dcshinMore effective c++ chapter1 2_dcshin
More effective c++ chapter1 2_dcshin
 
Visual studio 2010
Visual studio 2010Visual studio 2010
Visual studio 2010
 
C++ Advanced 강의 2주차
C++ Advanced 강의 2주차C++ Advanced 강의 2주차
C++ Advanced 강의 2주차
 
파이썬 스터디 9장
파이썬 스터디 9장파이썬 스터디 9장
파이썬 스터디 9장
 
[NDC2016] TERA 서버의 Modern C++ 활용기
[NDC2016] TERA 서버의 Modern C++ 활용기[NDC2016] TERA 서버의 Modern C++ 활용기
[NDC2016] TERA 서버의 Modern C++ 활용기
 
3.포인터
3.포인터3.포인터
3.포인터
 
포인터의기초 (2) - 포인터 사용하기1
포인터의기초 (2) - 포인터 사용하기1포인터의기초 (2) - 포인터 사용하기1
포인터의기초 (2) - 포인터 사용하기1
 
14장 - 15장 예외처리, 템플릿
14장 - 15장 예외처리, 템플릿14장 - 15장 예외처리, 템플릿
14장 - 15장 예외처리, 템플릿
 
강의자료4
강의자료4강의자료4
강의자료4
 
HI-ARC PS 101
HI-ARC PS 101HI-ARC PS 101
HI-ARC PS 101
 
[C++ Korea 2nd Seminar] C++17 Key Features Summary
[C++ Korea 2nd Seminar] C++17 Key Features Summary[C++ Korea 2nd Seminar] C++17 Key Features Summary
[C++ Korea 2nd Seminar] C++17 Key Features Summary
 
Composite Pattern
Composite PatternComposite Pattern
Composite Pattern
 
Modern C++의 타입 추론과 람다, 컨셉
Modern C++의 타입 추론과 람다, 컨셉Modern C++의 타입 추론과 람다, 컨셉
Modern C++의 타입 추론과 람다, 컨셉
 
RNC C++ lecture_2 operator, if
RNC C++ lecture_2 operator, ifRNC C++ lecture_2 operator, if
RNC C++ lecture_2 operator, if
 
6 function
6 function6 function
6 function
 
RNC C++ lecture_4 While, For
RNC C++ lecture_4 While, ForRNC C++ lecture_4 While, For
RNC C++ lecture_4 While, For
 

Mais de fefe7270

Surface flingerservice(서피스 출력 요청 jb)
Surface flingerservice(서피스 출력 요청 jb)Surface flingerservice(서피스 출력 요청 jb)
Surface flingerservice(서피스 출력 요청 jb)fefe7270
 
Surface flingerservice(서피스 플링거 연결 jb)
Surface flingerservice(서피스 플링거 연결 jb)Surface flingerservice(서피스 플링거 연결 jb)
Surface flingerservice(서피스 플링거 연결 jb)fefe7270
 
Surface flingerservice(서피스플링거서비스초기화 jb)
Surface flingerservice(서피스플링거서비스초기화 jb)Surface flingerservice(서피스플링거서비스초기화 jb)
Surface flingerservice(서피스플링거서비스초기화 jb)fefe7270
 
Surface flingerservice(서피스 플링거 연결 ics)
Surface flingerservice(서피스 플링거 연결 ics)Surface flingerservice(서피스 플링거 연결 ics)
Surface flingerservice(서피스 플링거 연결 ics)fefe7270
 
Surface flingerservice(서피스플링거서비스초기화 ics)
Surface flingerservice(서피스플링거서비스초기화 ics)Surface flingerservice(서피스플링거서비스초기화 ics)
Surface flingerservice(서피스플링거서비스초기화 ics)fefe7270
 
Surface flingerservice(그래픽 공유 버퍼 생성 및 등록)
Surface flingerservice(그래픽 공유 버퍼 생성 및 등록)Surface flingerservice(그래픽 공유 버퍼 생성 및 등록)
Surface flingerservice(그래픽 공유 버퍼 생성 및 등록)fefe7270
 
Surface flingerservice(서피스 상태 변경 및 출력 요청)
Surface flingerservice(서피스 상태 변경 및 출력 요청)Surface flingerservice(서피스 상태 변경 및 출력 요청)
Surface flingerservice(서피스 상태 변경 및 출력 요청)fefe7270
 
Surface flingerservice(서피스 플링거 연결)
Surface flingerservice(서피스 플링거 연결)Surface flingerservice(서피스 플링거 연결)
Surface flingerservice(서피스 플링거 연결)fefe7270
 
Surface flingerservice(서피스플링거서비스초기화)
Surface flingerservice(서피스플링거서비스초기화)Surface flingerservice(서피스플링거서비스초기화)
Surface flingerservice(서피스플링거서비스초기화)fefe7270
 
Android audio system(audioflinger)
Android audio system(audioflinger)Android audio system(audioflinger)
Android audio system(audioflinger)fefe7270
 
Android audio system(audiopolicy_manager)
Android audio system(audiopolicy_manager)Android audio system(audiopolicy_manager)
Android audio system(audiopolicy_manager)fefe7270
 
Android audio system(audioplicy_service)
Android audio system(audioplicy_service)Android audio system(audioplicy_service)
Android audio system(audioplicy_service)fefe7270
 
Android audio system(audio_hardwareinterace)
Android audio system(audio_hardwareinterace)Android audio system(audio_hardwareinterace)
Android audio system(audio_hardwareinterace)fefe7270
 
Android audio system(pcm데이터출력준비-서비스서버)
Android audio system(pcm데이터출력준비-서비스서버)Android audio system(pcm데이터출력준비-서비스서버)
Android audio system(pcm데이터출력준비-서비스서버)fefe7270
 
Android audio system(pcm데이터출력요청-서비스클라이언트)
Android audio system(pcm데이터출력요청-서비스클라이언트)Android audio system(pcm데이터출력요청-서비스클라이언트)
Android audio system(pcm데이터출력요청-서비스클라이언트)fefe7270
 
Android audio system(오디오 출력-트랙생성)
Android audio system(오디오 출력-트랙생성)Android audio system(오디오 출력-트랙생성)
Android audio system(오디오 출력-트랙생성)fefe7270
 
Android audio system(오디오 출력-트랙활성화)
Android audio system(오디오 출력-트랙활성화)Android audio system(오디오 출력-트랙활성화)
Android audio system(오디오 출력-트랙활성화)fefe7270
 
Android audio system(오디오 플링거 서비스 초기화)
Android audio system(오디오 플링거 서비스 초기화)Android audio system(오디오 플링거 서비스 초기화)
Android audio system(오디오 플링거 서비스 초기화)fefe7270
 

Mais de fefe7270 (18)

Surface flingerservice(서피스 출력 요청 jb)
Surface flingerservice(서피스 출력 요청 jb)Surface flingerservice(서피스 출력 요청 jb)
Surface flingerservice(서피스 출력 요청 jb)
 
Surface flingerservice(서피스 플링거 연결 jb)
Surface flingerservice(서피스 플링거 연결 jb)Surface flingerservice(서피스 플링거 연결 jb)
Surface flingerservice(서피스 플링거 연결 jb)
 
Surface flingerservice(서피스플링거서비스초기화 jb)
Surface flingerservice(서피스플링거서비스초기화 jb)Surface flingerservice(서피스플링거서비스초기화 jb)
Surface flingerservice(서피스플링거서비스초기화 jb)
 
Surface flingerservice(서피스 플링거 연결 ics)
Surface flingerservice(서피스 플링거 연결 ics)Surface flingerservice(서피스 플링거 연결 ics)
Surface flingerservice(서피스 플링거 연결 ics)
 
Surface flingerservice(서피스플링거서비스초기화 ics)
Surface flingerservice(서피스플링거서비스초기화 ics)Surface flingerservice(서피스플링거서비스초기화 ics)
Surface flingerservice(서피스플링거서비스초기화 ics)
 
Surface flingerservice(그래픽 공유 버퍼 생성 및 등록)
Surface flingerservice(그래픽 공유 버퍼 생성 및 등록)Surface flingerservice(그래픽 공유 버퍼 생성 및 등록)
Surface flingerservice(그래픽 공유 버퍼 생성 및 등록)
 
Surface flingerservice(서피스 상태 변경 및 출력 요청)
Surface flingerservice(서피스 상태 변경 및 출력 요청)Surface flingerservice(서피스 상태 변경 및 출력 요청)
Surface flingerservice(서피스 상태 변경 및 출력 요청)
 
Surface flingerservice(서피스 플링거 연결)
Surface flingerservice(서피스 플링거 연결)Surface flingerservice(서피스 플링거 연결)
Surface flingerservice(서피스 플링거 연결)
 
Surface flingerservice(서피스플링거서비스초기화)
Surface flingerservice(서피스플링거서비스초기화)Surface flingerservice(서피스플링거서비스초기화)
Surface flingerservice(서피스플링거서비스초기화)
 
Android audio system(audioflinger)
Android audio system(audioflinger)Android audio system(audioflinger)
Android audio system(audioflinger)
 
Android audio system(audiopolicy_manager)
Android audio system(audiopolicy_manager)Android audio system(audiopolicy_manager)
Android audio system(audiopolicy_manager)
 
Android audio system(audioplicy_service)
Android audio system(audioplicy_service)Android audio system(audioplicy_service)
Android audio system(audioplicy_service)
 
Android audio system(audio_hardwareinterace)
Android audio system(audio_hardwareinterace)Android audio system(audio_hardwareinterace)
Android audio system(audio_hardwareinterace)
 
Android audio system(pcm데이터출력준비-서비스서버)
Android audio system(pcm데이터출력준비-서비스서버)Android audio system(pcm데이터출력준비-서비스서버)
Android audio system(pcm데이터출력준비-서비스서버)
 
Android audio system(pcm데이터출력요청-서비스클라이언트)
Android audio system(pcm데이터출력요청-서비스클라이언트)Android audio system(pcm데이터출력요청-서비스클라이언트)
Android audio system(pcm데이터출력요청-서비스클라이언트)
 
Android audio system(오디오 출력-트랙생성)
Android audio system(오디오 출력-트랙생성)Android audio system(오디오 출력-트랙생성)
Android audio system(오디오 출력-트랙생성)
 
Android audio system(오디오 출력-트랙활성화)
Android audio system(오디오 출력-트랙활성화)Android audio system(오디오 출력-트랙활성화)
Android audio system(오디오 출력-트랙활성화)
 
Android audio system(오디오 플링거 서비스 초기화)
Android audio system(오디오 플링거 서비스 초기화)Android audio system(오디오 플링거 서비스 초기화)
Android audio system(오디오 플링거 서비스 초기화)
 

Último

Merge (Kitworks Team Study 이성수 발표자료 240426)
Merge (Kitworks Team Study 이성수 발표자료 240426)Merge (Kitworks Team Study 이성수 발표자료 240426)
Merge (Kitworks Team Study 이성수 발표자료 240426)Wonjun Hwang
 
A future that integrates LLMs and LAMs (Symposium)
A future that integrates LLMs and LAMs (Symposium)A future that integrates LLMs and LAMs (Symposium)
A future that integrates LLMs and LAMs (Symposium)Tae Young Lee
 
Continual Active Learning for Efficient Adaptation of Machine LearningModels ...
Continual Active Learning for Efficient Adaptation of Machine LearningModels ...Continual Active Learning for Efficient Adaptation of Machine LearningModels ...
Continual Active Learning for Efficient Adaptation of Machine LearningModels ...Kim Daeun
 
Console API (Kitworks Team Study 백혜인 발표자료)
Console API (Kitworks Team Study 백혜인 발표자료)Console API (Kitworks Team Study 백혜인 발표자료)
Console API (Kitworks Team Study 백혜인 발표자료)Wonjun Hwang
 
캐드앤그래픽스 2024년 5월호 목차
캐드앤그래픽스 2024년 5월호 목차캐드앤그래픽스 2024년 5월호 목차
캐드앤그래픽스 2024년 5월호 목차캐드앤그래픽스
 
MOODv2 : Masked Image Modeling for Out-of-Distribution Detection
MOODv2 : Masked Image Modeling for Out-of-Distribution DetectionMOODv2 : Masked Image Modeling for Out-of-Distribution Detection
MOODv2 : Masked Image Modeling for Out-of-Distribution DetectionKim Daeun
 

Último (6)

Merge (Kitworks Team Study 이성수 발표자료 240426)
Merge (Kitworks Team Study 이성수 발표자료 240426)Merge (Kitworks Team Study 이성수 발표자료 240426)
Merge (Kitworks Team Study 이성수 발표자료 240426)
 
A future that integrates LLMs and LAMs (Symposium)
A future that integrates LLMs and LAMs (Symposium)A future that integrates LLMs and LAMs (Symposium)
A future that integrates LLMs and LAMs (Symposium)
 
Continual Active Learning for Efficient Adaptation of Machine LearningModels ...
Continual Active Learning for Efficient Adaptation of Machine LearningModels ...Continual Active Learning for Efficient Adaptation of Machine LearningModels ...
Continual Active Learning for Efficient Adaptation of Machine LearningModels ...
 
Console API (Kitworks Team Study 백혜인 발표자료)
Console API (Kitworks Team Study 백혜인 발표자료)Console API (Kitworks Team Study 백혜인 발표자료)
Console API (Kitworks Team Study 백혜인 발표자료)
 
캐드앤그래픽스 2024년 5월호 목차
캐드앤그래픽스 2024년 5월호 목차캐드앤그래픽스 2024년 5월호 목차
캐드앤그래픽스 2024년 5월호 목차
 
MOODv2 : Masked Image Modeling for Out-of-Distribution Detection
MOODv2 : Masked Image Modeling for Out-of-Distribution DetectionMOODv2 : Masked Image Modeling for Out-of-Distribution Detection
MOODv2 : Masked Image Modeling for Out-of-Distribution Detection
 

C++정리 스마트포인터

  • 2. 1.스마트 포인터 정의 및 역활 c++정리-스마트포인터 1. 정의:임의의 객체가 다른 타입의 포인터 역할을 하는것. 2. 장점: 멤버 객체를 둘러싸고 있는 객체 이다. 즉, 생성/복사/대입/소멸의 모든 과정을 사용자가 제어 할 수 있다. 대표적 활용이 소멸자에서의 멤버 객체 자동 삭제 이다. 3. 역할 a. 멤버 객체를 소멸자에서 자동으로 delete한다. b. 스마트 포인터 객체로 멤버 객체에 접근 할 수 있다. c. 모든 type에 대해서 스마트 포인터를 사용 할 수 있다. d. 얕은 복사 문제를 해결할 수 있다.
  • 3. a. 멤버 객체를 소멸자에서 자동으로 delete한다. c++정리-스마트포인터 class Car { public: void Go() { cout << "Car Go" << endl; } }; class ptr { Car* obj; public: ptr( Car* p = 0 ) : obj(p) {} //생성자에서 p를 obj로 넣어준다. //ptr이 객체이기 때문에 함수를 벗어날때 소멸자를 불러준다. //그래서 생성한 obj를 delete하는 code를 넣어주면 사용자가 따로 obj를 delete하는 // code를 넣을 필요가 없다. ~ptr() { delete obj; } } int main() { ptr p = new Car; // ptr p( new Car ) 와 같다. }
  • 4. b. 스마트 포인터 객체로 멤버 객체에 접근 할 수 있다. c++정리-스마트포인터 class Car { public: void Go() { cout << "Car Go" << endl; } }; class ptr { Car* obj; public: ptr( Car* p = 0 ) : obj(p) {} //생성자에서 p를 obj로 copy한다. ~ptr() { delete obj; } Car* operator->() { return obj; }  객체 멤버에 접근하기 위한 ‘->’ 재정의 Car& operator*() { return *obj; }  객체 멤버에 접근하기 위한 ‘*’ 재정의 } int main() { ptr p = new Car; // ptr p( new Car ) p->Go();//OK Car의 go 호출 p->  p.operator->() 호출. (*p).GO(); //OK Car의 go 호출 *p  p.operator*() 호출. }
  • 5. c. 모든 type에 대해서 스마트 포인터를 사용 할 수 있다. c++정리-스마트포인터 template으로 만들어야 한다. template<typename T> class ptr  typename T에 대한 스마트 포인터를 사용할 수 있다. { T* obj; public: ptr( T* p = 0 ) : obj(p) {}  생성자에서 type T의 객체를 obj로 복사 ~ptr() { delete obj; }  소멸자에서 자동으로 obj 삭제 T* operator->() { return obj; } T& operator*() { return *obj; } type T의 객체에 접근 하기 위한 연산자 재정의 };
  • 6. d. 얕은 복사 문제를 해결할 수 있다. c++정리-스마트포인터 1)소유권 이전 방법 사용 template<typename T> class ptr { T* obj; public: ptr( ptr& p ) : obj(p.obj) //먼저 얕은 복사를 하고. { p.obj = 0; // 기존 포인터는 reset 한다.(이전 스마트 포인터의 소유권을 포기한다.) } ptr( T* p = 0 ) : obj(p) {} //생성자 ~ptr() { delete obj; } //소멸자 T* operator->() { return obj; } //연산자 재정의 T& operator*() { return *obj; } }; int main() { ptr<int> p1 = new int; *p1 = 10; ptr<int> p2 = p1; // 이 순간 공유가 아니라 p2로 자원이 전달됩니다. cout << *p1 << endl; // 1.. runtime error.. cout << *p2 << endl; // 2. ok.. } Cf. c++ 표준 library(STL)에는 소유권 이전 스마트 포인터인 auto_prt<> 이 있다. int main() { auto_ptr<int> p1( new int ); *p1 = 10; auto_ptr<int> p2(p1); // 소유권 이전 cout << *p1 << endl; // runtime error cout << *p2 << endl; // 10 }
  • 7. d. 얕은 복사 문제를 해결할 수 있다. c++정리-스마트포인터 2)참조 계수 기반의 스마트 포인터 template<typename T> class ptr int main() { { T* obj; ptr<int> p1 = new int; int* ref; // 참조계수를 위한 변수 public: *p1 = 10; ptr( T* p = 0 ) : obj(p) { ptr<int> p2 = p1; ref = new int(1); //생성자에서 참조 계수 생성. } cout << *p1 << endl; //ok 10 cout << *p2 << endl; //ok 10 //참조계수로 구현한 복사 생성자 } ptr( const ptr& p ) : obj(p.obj), ref(p.ref) { ++(*ref); } //소멸자 ~ptr() { Cf. c++ 표준 library(STL)에는 참조 계수 기반의 스마트 포인터인 if ( --(*ref) == 0 ) //ref가 0일 경우만 객체 delete shared_ptr<> 가 있다. { int main() delete obj; { delete ref; shared_ptr<int> p1( new int); } *p1 = 10; } shared_ptr<int> p2(p1);//p1의 멤버가 p2로 copy되면서 참조계수 1증가. cout << *p1 << endl; //ok 10 cout << *p2 << endl; //ok 10 T* operator->() { return obj; } } T& operator*() { return *obj; } };
  • 8. d. 얕은 복사 문제를 해결할 수 있다. c++정리-스마트포인터 3) 객체 내부에 참조계수를 관리하자. 스마트 포인터의 생성자,소멸자에서 객체 내부의 incstrong,decstrong을 호출하게 하자. 객체 내부에 mCount 참조계수 관리 스마트 포인터의 생성자,소멸자에서 객체 내부의 incstrong,decstrong을 호출 함 class Car { template<typename T> class sp int mCount; //참조 계수 { public: T* m_ptr; public: Car() : mCount(0) {}//생성자 void incStrong() { ++mCount; } //생성자 void decStrong() sp( T* other = 0 ) : m_ptr(other) { { if ( --mCount == 0 ) delete this; // 자신을 스스로 파괴 함. if ( m_ptr ) m_ptr->incStrong(); //객체의 incStrong 호출 } } }; //복사생성자 sp( const sp& p ) : m_ptr( p.m_ptr ) { if ( m_ptr ) m_ptr->incStrong(); //객체의 incStrong 호출 } int main() { //소멸자 ~sp() sp<Car> p1 = new Car;// 생성자에서 incStrong 부름. { if ( m_ptr ) m_ptr->decStrong(); //객체의 decStrong 호출 sp<Car> p2 = p1; } //복사생성자에서 incStrong 부름. p2=new Car(p1); 와 같음. }; sp<int> p3 = new int; //error int class에서 incStrong , decStrong 이 없다. 그래서, 안드로이드에서는 최상위 부모 class인 Refbase에 incStrong, decStrong 을 정의해 놓고 상속받아서 사용하게 되어있다. }
  • 9. 안드로이드에서의 스마트 포인터 사용 예 c++정리-스마트포인터 -안드로이드에서는 Strongpointer 객체로 스마트 포인터 기능을 구현한다. 또한, 최상위 class인 Refbase에 참조계수가 정의 되어 있다.(incStrong, decStrong ) StrongPointer.h //소멸자 정의 template <typename T> sp<T>::~sp() class sp { { if (m_ptr) m_ptr->decStrong(this); public: } sp(T* other); //생성자 선언 결론적으로 안드로이드에서는 최상위 class인 Refbas의 sp(const sp<T>& other); //복사 생성자 선언 incStrong,decStrong이 불리게 된다. ~sp(); //소멸자 선언 //연산자 재정의 Refbase.h inline T& operator* () const { return *m_ptr; } class RefBase inline T* operator-> () const { return m_ptr; } { inline T* get() const { return m_ptr; } public: void incStrong(const void* id) const; private: void decStrong(const void* id) const; T* m_ptr; … } } //생성자 정의 template<typename T> Refbase.cpp sp<T>::sp(T* other) void RefBase::incStrong(const void* id) const : m_ptr(other) { { //참조 계수 값 증가 if (other) other->incStrong(this); T의 incStrong 호출 const int32_t c = android_atomic_inc(&refs->mStrong); } } //복사생성자 정의 template<typename T> void RefBase::decStrong(const void* id) const sp<T>::sp(const sp<T>& other) { : m_ptr(other.m_ptr) //참조 계수 값 감소 { const int32_t c = android_atomic_dec(&refs->mStrong); if (m_ptr) m_ptr->incStrong(this); } }