SlideShare uma empresa Scribd logo
1 de 61
Baixar para ler offline
Effective Modern C++ Study
C++ Korea
Item 17 : Understand special member function generation.
Item 18 : Use std::unique_ptr for exclusive-ownership resource
management.
Item 19 : Use std::shared_ptr for shared-ownership resource management
.
Effective Modern C++ Study
C++ Korea3
Effective Modern C++ Study
C++ Korea4
Effective Modern C++ Study
C++ Korea5
Effective Modern C++ Study
C++ Korea6
Effective Modern C++ Study
C++ Korea7
Effective Modern C++ Study
C++ Korea8
Effective Modern C++ Study
C++ Korea9
Effective Modern C++ Study
C++ Korea10
Effective Modern C++ Study
C++ Korea12
Effective Modern C++ Study
C++ Korea13
Effective Modern C++ Study
C++ Korea14
Effective Modern C++ Study
C++ Korea15
Effective Modern C++ Study
C++ Korea16
Effective Modern C++ Study
C++ Korea17
Effective Modern C++ Study
C++ Korea18
Effective Modern C++ Study
C++ Korea19
Effective Modern C++ Study
C++ Korea20
Effective Modern C++ Study
C++ Korea21
Effective Modern C++ Study
C++ Korea22
Effective Modern C++ Study
C++ Korea23
Effective Modern C++ Study
C++ Korea24
Effective Modern C++ Study
C++ Korea25
Effective Modern C++ Study
C++ Korea26
Effective Modern C++ Study
C++ Korea27
Effective Modern C++ Study
C++ Korea28
Effective Modern C++ Study
C++ Korea29
Effective Modern C++ Study
C++ Korea30
Effective Modern C++ Study
C++ Korea31
Effective Modern C++ Study
C++ Korea32
Effective Modern C++ Study
C++ Korea33
Effective Modern C++ Study
C++ Korea34
Effective Modern C++ Study
C++ Korea38
 1959년 LISP의 문제를 해결하기 위해 John McCarthy가 개발
 Java, C#, 대부분의 Script 언어에서 쓰이고 있음
 장점(버그를 줄이거나 완전히 막아줌)
- 유효하지 않은 포인터에 접근
- 이중 해제
- Memory Leak
 단점(주로 성능적 이슈)
- GC 알고리즘의 오버헤드
(프로그래머는 빤히 아는데… 왜 그걸 굳이 또 계산해가면서…)
- Timing 예측 불가 (중요한 타이밍에 버벅)
- 자원해제 시점을 모른다.
http://ko.wikipedia.org/wiki/쓰레기_수집_(컴퓨터_과학)
GC의 장점 + !단점이 가능할까 ?
Effective Modern C++ Study
C++ Korea40
• 직접적으로 Object를 소유하지 않음
• 여러 개의 std::shared_ptr이 하나의 Object를 공유
• Object는 마지막 std::shared_ptr이 사라지면 해제
#include <memory>
GC의 장점 : Object의 수명에 대해 신경 쓸 필요가 없다.
!단점 : 원하는 시점에 해제가 가능하다.
• 사용법은 생략
• 참조 사이트 : http://devluna.blogspot.kr/2014/12/stl-sharedptr-weakptr.html
Effective Modern C++ Study
C++ Korea42
 해당 Object를 참조하고 있는 std::shared_ptr 의 개수
 std::shared_ptr Constructor : Ref. Count ++
 std::shared_ptr Destructor : Ref. Count - -
 std::shared_ptr ::operator = : Left-hand Ref. Count ++, Right-hand Ref. Count - -
 Atfer Ref. Count - - , if Ref. Count == 0 then delete object
Effective Modern C++ Study
C++ Korea43
1. Memory Issue
• Raw Pointer 크기의 2배 : Object Pointer + Control Block Pointer (include Ref. Count)
• Heap Memory (Dynamic Allocation) : Object 자체는 Ref. Count가 필요가 없다.
2. Performance Issue
• Atomic 연산 (sizse는 word)
• 대부분의 std::shared_ptr 은 Ref. Count ++
(Move 생성자, Move 연산자는 Ref. Count 변화 없음)
Effective Modern C++ Study
C++ Korea45
auto LogDel = [](T *pw)
{
makeLog(pw);
delete pw;
};
std::unique_ptr<T, decltype(LogDel)> UPW(new T, LogDel); // deleter type is part of ptr type
std::shared_ptr<T> SPW(new T, LogDel); // deleter type is not part of ptr type
- std::unique_ptr : template type의 부분
- std::shared_ptr : type의 일부가 아님
서로 다른 deleter를 가진 std::shared_ptr을 하나의 Container에 담을 수 있다.
Effective Modern C++ Study
C++ Korea46
- std::unique_ptr 은 custom deleter 크기를 포함
- std::shared_ptr 은 custom deleter 여부와 상관없이 무조건 Pointer 2개의 크기
• custom deleter는 function object 이다.
• 그럼 어디 저장 될까 ?
Control Block에 저장된다.
Effective Modern C++ Study
C++ Korea48
- Reference Count
- Weak Count
- Custom Deleter (if exists)
- Allocator (if exists)
Effective Modern C++ Study
C++ Korea49
- std::make_shared
- Unique-ownership Pointer (std::unique_ptr, std::auto_ptr)로 부터
std::shared_ptr 을 만들 때
- Raw Pointer로부터 std::shared_ptr 을 만들 때
OK
OK (std::shared_ptr 로 부터 std::unique_ptr 는 불가능 하니깐)
가만 ! 딱 봐도 먼가 이상한 Smell 이…. 스멜스멜….
Effective Modern C++ Study
C++ Korea50
auto P = new T;
{
std::shared_ptr<T> SP1(P, makeLog); // create control block for *p
{
std::shared_ptr<T> SP2(P, makeLog);// create 2nd control block for *p
}
}
여기서 SP2의 Ref. Count == 0 이 되니, P의 dtor가 호출.
여기서 SP1의 Ref. Count == 0 이 되니, P의 dtor가 호출.
가만…. 이미 P는 해제됬는데… 아놔 어떡하지 ???
1. Raw Pointer로 부터 std::shared_ptr을 생성하지 말자.
(하지만, custom deleter를 사용할려면 std::make_shared를 사용 못하는데 ???)
2. 어쩔수 없다면 Raw Pointer를 변수에 담지말고 new로 생성한 R-Value를 사용
std::shared_ptr<T> SP(new T, LogDel); // direct use of new
Effective Modern C++ Study
C++ Korea52
std::vector<std::shared_ptr<T>> T_History;
class T
{
public:
void process();
};
void T::process()
{
T_History.emplace_back(this); // this is wrong
}
this는 Raw Pointer
*this의 Control Block는 계속해서 만들어 질 것이다.
Effective Modern C++ Study
C++ Korea53
class T : public std::enable_shared_from_this<T>
{
public:
void process();
};
void T::process()
{
T_History.emplace_back( shared_from_this() );
}
근데… 너 좀 낮설다.
파생 클래스에서 파생 클래스의 템플릿 클래스를 상속받는다 ?
The Curiously Recurring Template Pattern (CRTP)
this로부터 std::shared_ptr은 만들지만 Control Block은 안만든다.
그런데…. 만약 그전에 만들어진 Control Block이 없다면 ?
아놔~ 예외를 발생시킨다.
어떻하지 ????
Factory Method Pattern
http://devluna.blogspot.kr/2015/01/factory-method-pattern.html
Effective Modern C++ Study
C++ Korea54
class T : public std::enable_shared_from_this<T>
{
public:
template<typename... Ts>
static std::shared_ptr<T> create(Ts&&... params);
private:
template<typename... Ts>
T(Ts&&... params);
};
생성자를 private에 선언
Factory method에서 std::shared<T>를 return
Effective Modern C++ Study
C++ Korea56
• Dynamic Allocation
• Size : few Words + custom deleter, allocator
• Virtual Function
• Atomic Calculation
Default는 3 Words
std::make_shared
Object Destructor
1,2 Instruction Cycle
이정도 Cost만 감당한다면, 수명관리를 해준다.
Effective Modern C++ Study
C++ Korea58
• std::shared_ptr는 단일 Pointer에 대해서만 동작
• 그럼 delete[ ] 를 이용해서 custom deleter를 만들면 ?
• std::shared_ptr에는 [ ] 연산자가 없다.
• 결정적으로 단일 개체에 대해서만 derived-to-base 포인트 변환을 지원
Effective Modern C++ Study
C++ Korea60
• std::shared_ptr는 개체에 대한 수명관리를 Garbage Collection 만큼 편리하게 해준다.
• std::unique_ptr에 비해 std::shared_ptr는 개체가 2배 더 크고, Control Block에 대한 오버해
드가 발생하고, Reference Count에 대해서 Atomic 연산을 해야 한다.
• default 자원해제는 delete 지만 custom deleter도 지원한다. deleter의 타입은 std::shared_ptr
의 타입에 영향을 미치지 않는다.
• Raw Pointer를 변수로 만들어서 std::shared_ptr로 만들지 마라.
http://devluna.blogspot.kr/2015/02/item-19-stdsharedptr.html
icysword77@gmail.com

Mais conteúdo relacionado

Mais procurados

Chapitre4: Pointeurs et références
Chapitre4: Pointeurs et références Chapitre4: Pointeurs et références
Chapitre4: Pointeurs et références Aziz Darouichi
 
Chapitre6: Surcharge des opérateurs
Chapitre6:  Surcharge des opérateursChapitre6:  Surcharge des opérateurs
Chapitre6: Surcharge des opérateursAziz Darouichi
 
C++コミュニティーの中心でC++をDISる
C++コミュニティーの中心でC++をDISるC++コミュニティーの中心でC++をDISる
C++コミュニティーの中心でC++をDISるHideyuki Tanaka
 
Effective Modern C++ 勉強会 Item 22
Effective Modern C++ 勉強会 Item 22Effective Modern C++ 勉強会 Item 22
Effective Modern C++ 勉強会 Item 22Keisuke Fukuda
 
C++17 Key Features Summary - Ver 2
C++17 Key Features Summary - Ver 2C++17 Key Features Summary - Ver 2
C++17 Key Features Summary - Ver 2Chris Ohk
 
Cours structures des données (langage c)
Cours structures des données (langage c)Cours structures des données (langage c)
Cours structures des données (langage c)rezgui mohamed
 
Seance 3- Programmation en langage C
Seance 3- Programmation en langage C Seance 3- Programmation en langage C
Seance 3- Programmation en langage C Fahad Golra
 
Chapitre1: Langage Python
Chapitre1: Langage PythonChapitre1: Langage Python
Chapitre1: Langage PythonAziz Darouichi
 
Chapitre2fonctionscppv2019
Chapitre2fonctionscppv2019Chapitre2fonctionscppv2019
Chapitre2fonctionscppv2019Aziz Darouichi
 
POO Java Chapitre 6 Exceptions
POO Java  Chapitre 6 ExceptionsPOO Java  Chapitre 6 Exceptions
POO Java Chapitre 6 ExceptionsMouna Torjmen
 
Partie 11: Héritage — Programmation orientée objet en C++
Partie 11: Héritage — Programmation orientée objet en C++Partie 11: Héritage — Programmation orientée objet en C++
Partie 11: Héritage — Programmation orientée objet en C++Fabio Hernandez
 
Chap3 programmation modulaire en python
Chap3 programmation modulaire en pythonChap3 programmation modulaire en python
Chap3 programmation modulaire en pythonMariem ZAOUALI
 
C++のSTLのコンテナ型を概観する @ Ohotech 特盛 #10(2014.8.30)
C++のSTLのコンテナ型を概観する @ Ohotech 特盛 #10(2014.8.30)C++のSTLのコンテナ型を概観する @ Ohotech 特盛 #10(2014.8.30)
C++のSTLのコンテナ型を概観する @ Ohotech 特盛 #10(2014.8.30)Hiro H.
 
Chapitre8: Collections et Enumerations En Java
Chapitre8: Collections et Enumerations En JavaChapitre8: Collections et Enumerations En Java
Chapitre8: Collections et Enumerations En JavaAziz Darouichi
 

Mais procurados (20)

Chapitre4: Pointeurs et références
Chapitre4: Pointeurs et références Chapitre4: Pointeurs et références
Chapitre4: Pointeurs et références
 
Chapitre6: Surcharge des opérateurs
Chapitre6:  Surcharge des opérateursChapitre6:  Surcharge des opérateurs
Chapitre6: Surcharge des opérateurs
 
Emcjp item21
Emcjp item21Emcjp item21
Emcjp item21
 
Emcpp0506
Emcpp0506Emcpp0506
Emcpp0506
 
C++コミュニティーの中心でC++をDISる
C++コミュニティーの中心でC++をDISるC++コミュニティーの中心でC++をDISる
C++コミュニティーの中心でC++をDISる
 
Effective Modern C++ 勉強会 Item 22
Effective Modern C++ 勉強会 Item 22Effective Modern C++ 勉強会 Item 22
Effective Modern C++ 勉強会 Item 22
 
C++17 Key Features Summary - Ver 2
C++17 Key Features Summary - Ver 2C++17 Key Features Summary - Ver 2
C++17 Key Features Summary - Ver 2
 
Oops presentation
Oops presentationOops presentation
Oops presentation
 
Cours structures des données (langage c)
Cours structures des données (langage c)Cours structures des données (langage c)
Cours structures des données (langage c)
 
Seance 3- Programmation en langage C
Seance 3- Programmation en langage C Seance 3- Programmation en langage C
Seance 3- Programmation en langage C
 
Chapitre1: Langage Python
Chapitre1: Langage PythonChapitre1: Langage Python
Chapitre1: Langage Python
 
Chapitre2fonctionscppv2019
Chapitre2fonctionscppv2019Chapitre2fonctionscppv2019
Chapitre2fonctionscppv2019
 
POO Java Chapitre 6 Exceptions
POO Java  Chapitre 6 ExceptionsPOO Java  Chapitre 6 Exceptions
POO Java Chapitre 6 Exceptions
 
pile file.pptx
pile file.pptxpile file.pptx
pile file.pptx
 
Partie 11: Héritage — Programmation orientée objet en C++
Partie 11: Héritage — Programmation orientée objet en C++Partie 11: Héritage — Programmation orientée objet en C++
Partie 11: Héritage — Programmation orientée objet en C++
 
Introduction à Python
Introduction à PythonIntroduction à Python
Introduction à Python
 
Chap1: Cours en C++
Chap1: Cours en C++Chap1: Cours en C++
Chap1: Cours en C++
 
Chap3 programmation modulaire en python
Chap3 programmation modulaire en pythonChap3 programmation modulaire en python
Chap3 programmation modulaire en python
 
C++のSTLのコンテナ型を概観する @ Ohotech 特盛 #10(2014.8.30)
C++のSTLのコンテナ型を概観する @ Ohotech 特盛 #10(2014.8.30)C++のSTLのコンテナ型を概観する @ Ohotech 特盛 #10(2014.8.30)
C++のSTLのコンテナ型を概観する @ Ohotech 特盛 #10(2014.8.30)
 
Chapitre8: Collections et Enumerations En Java
Chapitre8: Collections et Enumerations En JavaChapitre8: Collections et Enumerations En Java
Chapitre8: Collections et Enumerations En Java
 

Semelhante a [C++ korea] effective modern c++ study item 17 19 신촌 study

[C++ Korea] Effective Modern C++ Study item 31-33
[C++ Korea] Effective Modern C++ Study item 31-33[C++ Korea] Effective Modern C++ Study item 31-33
[C++ Korea] Effective Modern C++ Study item 31-33Seok-joon Yun
 
[C++ korea] Effective Modern C++ study item 19 use shared ptr for shared owne...
[C++ korea] Effective Modern C++ study item 19 use shared ptr for shared owne...[C++ korea] Effective Modern C++ study item 19 use shared ptr for shared owne...
[C++ korea] Effective Modern C++ study item 19 use shared ptr for shared owne...Seok-joon Yun
 
Item22 when using the pimpl idiom, define special memberfuctions in the imple...
Item22 when using the pimpl idiom, define special memberfuctions in the imple...Item22 when using the pimpl idiom, define special memberfuctions in the imple...
Item22 when using the pimpl idiom, define special memberfuctions in the imple...건 손
 
[NDC2016] TERA 서버의 Modern C++ 활용기
[NDC2016] TERA 서버의 Modern C++ 활용기[NDC2016] TERA 서버의 Modern C++ 활용기
[NDC2016] TERA 서버의 Modern C++ 활용기Sang Heon Lee
 
C++20 Key Features Summary
C++20 Key Features SummaryC++20 Key Features Summary
C++20 Key Features SummaryChris Ohk
 
[C++ Korea] C++ 메모리 모델과 atomic 타입 연산들
[C++ Korea] C++ 메모리 모델과 atomic 타입 연산들[C++ Korea] C++ 메모리 모델과 atomic 타입 연산들
[C++ Korea] C++ 메모리 모델과 atomic 타입 연산들DongMin Choi
 
파이썬 스터디 9장
파이썬 스터디 9장파이썬 스터디 9장
파이썬 스터디 9장SeongHyun Ahn
 
객체지향 정리. Part1
객체지향 정리. Part1객체지향 정리. Part1
객체지향 정리. Part1kim HYUNG JIN
 
파이썬 데이터과학 레벨1 - 초보자를 위한 데이터분석, 데이터시각화 (2020년 이태영)
파이썬 데이터과학 레벨1 - 초보자를 위한 데이터분석, 데이터시각화 (2020년 이태영) 파이썬 데이터과학 레벨1 - 초보자를 위한 데이터분석, 데이터시각화 (2020년 이태영)
파이썬 데이터과학 레벨1 - 초보자를 위한 데이터분석, 데이터시각화 (2020년 이태영) Tae Young Lee
 
[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
 
C++ 11 에 대해서 쉽게 알아봅시다 1부
C++ 11 에 대해서 쉽게 알아봅시다 1부C++ 11 에 대해서 쉽게 알아봅시다 1부
C++ 11 에 대해서 쉽게 알아봅시다 1부Gwangwhi Mah
 
Lecture 1: Introduction to Python and TensorFlow
Lecture 1: Introduction to Python and TensorFlowLecture 1: Introduction to Python and TensorFlow
Lecture 1: Introduction to Python and TensorFlowSang Jun Lee
 
[C++ Korea] Effective Modern C++ Study, Item 1 - 3
[C++ Korea] Effective Modern C++ Study, Item 1 - 3[C++ Korea] Effective Modern C++ Study, Item 1 - 3
[C++ Korea] Effective Modern C++ Study, Item 1 - 3Chris Ohk
 
Effective c++ 정리 chapter 4
Effective c++ 정리 chapter 4Effective c++ 정리 chapter 4
Effective c++ 정리 chapter 4연우 김
 
effective c++ chapter 3~4 정리
effective c++ chapter 3~4 정리effective c++ chapter 3~4 정리
effective c++ chapter 3~4 정리Injae Lee
 
Visual studio 2010
Visual studio 2010Visual studio 2010
Visual studio 2010MinGeun Park
 
모던 C++ 정리
모던 C++ 정리모던 C++ 정리
모던 C++ 정리Hansol Kang
 
김재석, C++ 게임 개발자를 위한 c# 활용 기법, 월간 마이크로소프트웨어 창간 28주년 기념 C++ 개발자를 위한 게임 프로그래밍 실전...
김재석, C++ 게임 개발자를 위한 c# 활용 기법, 월간 마이크로소프트웨어 창간 28주년 기념 C++ 개발자를 위한 게임 프로그래밍 실전...김재석, C++ 게임 개발자를 위한 c# 활용 기법, 월간 마이크로소프트웨어 창간 28주년 기념 C++ 개발자를 위한 게임 프로그래밍 실전...
김재석, C++ 게임 개발자를 위한 c# 활용 기법, 월간 마이크로소프트웨어 창간 28주년 기념 C++ 개발자를 위한 게임 프로그래밍 실전...devCAT Studio, NEXON
 
[C++ Korea] Effective Modern C++ mva item 7 distinguish between and {} when c...
[C++ Korea] Effective Modern C++ mva item 7 distinguish between and {} when c...[C++ Korea] Effective Modern C++ mva item 7 distinguish between and {} when c...
[C++ Korea] Effective Modern C++ mva item 7 distinguish between and {} when c...Seok-joon Yun
 
불어오는 변화의 바람, From c++98 to c++11, 14
불어오는 변화의 바람, From c++98 to c++11, 14 불어오는 변화의 바람, From c++98 to c++11, 14
불어오는 변화의 바람, From c++98 to c++11, 14 명신 김
 

Semelhante a [C++ korea] effective modern c++ study item 17 19 신촌 study (20)

[C++ Korea] Effective Modern C++ Study item 31-33
[C++ Korea] Effective Modern C++ Study item 31-33[C++ Korea] Effective Modern C++ Study item 31-33
[C++ Korea] Effective Modern C++ Study item 31-33
 
[C++ korea] Effective Modern C++ study item 19 use shared ptr for shared owne...
[C++ korea] Effective Modern C++ study item 19 use shared ptr for shared owne...[C++ korea] Effective Modern C++ study item 19 use shared ptr for shared owne...
[C++ korea] Effective Modern C++ study item 19 use shared ptr for shared owne...
 
Item22 when using the pimpl idiom, define special memberfuctions in the imple...
Item22 when using the pimpl idiom, define special memberfuctions in the imple...Item22 when using the pimpl idiom, define special memberfuctions in the imple...
Item22 when using the pimpl idiom, define special memberfuctions in the imple...
 
[NDC2016] TERA 서버의 Modern C++ 활용기
[NDC2016] TERA 서버의 Modern C++ 활용기[NDC2016] TERA 서버의 Modern C++ 활용기
[NDC2016] TERA 서버의 Modern C++ 활용기
 
C++20 Key Features Summary
C++20 Key Features SummaryC++20 Key Features Summary
C++20 Key Features Summary
 
[C++ Korea] C++ 메모리 모델과 atomic 타입 연산들
[C++ Korea] C++ 메모리 모델과 atomic 타입 연산들[C++ Korea] C++ 메모리 모델과 atomic 타입 연산들
[C++ Korea] C++ 메모리 모델과 atomic 타입 연산들
 
파이썬 스터디 9장
파이썬 스터디 9장파이썬 스터디 9장
파이썬 스터디 9장
 
객체지향 정리. Part1
객체지향 정리. Part1객체지향 정리. Part1
객체지향 정리. Part1
 
파이썬 데이터과학 레벨1 - 초보자를 위한 데이터분석, 데이터시각화 (2020년 이태영)
파이썬 데이터과학 레벨1 - 초보자를 위한 데이터분석, 데이터시각화 (2020년 이태영) 파이썬 데이터과학 레벨1 - 초보자를 위한 데이터분석, 데이터시각화 (2020년 이태영)
파이썬 데이터과학 레벨1 - 초보자를 위한 데이터분석, 데이터시각화 (2020년 이태영)
 
[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
 
C++ 11 에 대해서 쉽게 알아봅시다 1부
C++ 11 에 대해서 쉽게 알아봅시다 1부C++ 11 에 대해서 쉽게 알아봅시다 1부
C++ 11 에 대해서 쉽게 알아봅시다 1부
 
Lecture 1: Introduction to Python and TensorFlow
Lecture 1: Introduction to Python and TensorFlowLecture 1: Introduction to Python and TensorFlow
Lecture 1: Introduction to Python and TensorFlow
 
[C++ Korea] Effective Modern C++ Study, Item 1 - 3
[C++ Korea] Effective Modern C++ Study, Item 1 - 3[C++ Korea] Effective Modern C++ Study, Item 1 - 3
[C++ Korea] Effective Modern C++ Study, Item 1 - 3
 
Effective c++ 정리 chapter 4
Effective c++ 정리 chapter 4Effective c++ 정리 chapter 4
Effective c++ 정리 chapter 4
 
effective c++ chapter 3~4 정리
effective c++ chapter 3~4 정리effective c++ chapter 3~4 정리
effective c++ chapter 3~4 정리
 
Visual studio 2010
Visual studio 2010Visual studio 2010
Visual studio 2010
 
모던 C++ 정리
모던 C++ 정리모던 C++ 정리
모던 C++ 정리
 
김재석, C++ 게임 개발자를 위한 c# 활용 기법, 월간 마이크로소프트웨어 창간 28주년 기념 C++ 개발자를 위한 게임 프로그래밍 실전...
김재석, C++ 게임 개발자를 위한 c# 활용 기법, 월간 마이크로소프트웨어 창간 28주년 기념 C++ 개발자를 위한 게임 프로그래밍 실전...김재석, C++ 게임 개발자를 위한 c# 활용 기법, 월간 마이크로소프트웨어 창간 28주년 기념 C++ 개발자를 위한 게임 프로그래밍 실전...
김재석, C++ 게임 개발자를 위한 c# 활용 기법, 월간 마이크로소프트웨어 창간 28주년 기념 C++ 개발자를 위한 게임 프로그래밍 실전...
 
[C++ Korea] Effective Modern C++ mva item 7 distinguish between and {} when c...
[C++ Korea] Effective Modern C++ mva item 7 distinguish between and {} when c...[C++ Korea] Effective Modern C++ mva item 7 distinguish between and {} when c...
[C++ Korea] Effective Modern C++ mva item 7 distinguish between and {} when c...
 
불어오는 변화의 바람, From c++98 to c++11, 14
불어오는 변화의 바람, From c++98 to c++11, 14 불어오는 변화의 바람, From c++98 to c++11, 14
불어오는 변화의 바람, From c++98 to c++11, 14
 

Mais de Seok-joon Yun

Retrospective.2020 03
Retrospective.2020 03Retrospective.2020 03
Retrospective.2020 03Seok-joon Yun
 
AWS DEV DAY SEOUL 2017 Buliding Serverless Web App - 직방 Image Converter
AWS DEV DAY SEOUL 2017 Buliding Serverless Web App - 직방 Image ConverterAWS DEV DAY SEOUL 2017 Buliding Serverless Web App - 직방 Image Converter
AWS DEV DAY SEOUL 2017 Buliding Serverless Web App - 직방 Image ConverterSeok-joon Yun
 
아파트 시세,어쩌다 머신러닝까지
아파트 시세,어쩌다 머신러닝까지아파트 시세,어쩌다 머신러닝까지
아파트 시세,어쩌다 머신러닝까지Seok-joon Yun
 
Pro typescript.ch07.Exception, Memory, Performance
Pro typescript.ch07.Exception, Memory, PerformancePro typescript.ch07.Exception, Memory, Performance
Pro typescript.ch07.Exception, Memory, PerformanceSeok-joon Yun
 
Doing math with python.ch07
Doing math with python.ch07Doing math with python.ch07
Doing math with python.ch07Seok-joon Yun
 
Doing math with python.ch06
Doing math with python.ch06Doing math with python.ch06
Doing math with python.ch06Seok-joon Yun
 
Doing math with python.ch05
Doing math with python.ch05Doing math with python.ch05
Doing math with python.ch05Seok-joon Yun
 
Doing math with python.ch04
Doing math with python.ch04Doing math with python.ch04
Doing math with python.ch04Seok-joon Yun
 
Doing math with python.ch03
Doing math with python.ch03Doing math with python.ch03
Doing math with python.ch03Seok-joon Yun
 
Doing mathwithpython.ch02
Doing mathwithpython.ch02Doing mathwithpython.ch02
Doing mathwithpython.ch02Seok-joon Yun
 
Doing math with python.ch01
Doing math with python.ch01Doing math with python.ch01
Doing math with python.ch01Seok-joon Yun
 
Pro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptPro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptSeok-joon Yun
 
C++ Concurrency in Action 9-2 Interrupting threads
C++ Concurrency in Action 9-2 Interrupting threadsC++ Concurrency in Action 9-2 Interrupting threads
C++ Concurrency in Action 9-2 Interrupting threadsSeok-joon Yun
 
Welcome to Modern C++
Welcome to Modern C++Welcome to Modern C++
Welcome to Modern C++Seok-joon Yun
 
[2015-07-20-윤석준] Oracle 성능 관리 2
[2015-07-20-윤석준] Oracle 성능 관리 2[2015-07-20-윤석준] Oracle 성능 관리 2
[2015-07-20-윤석준] Oracle 성능 관리 2Seok-joon Yun
 
[2015-07-10-윤석준] Oracle 성능 관리 & v$sysstat
[2015-07-10-윤석준] Oracle 성능 관리 & v$sysstat[2015-07-10-윤석준] Oracle 성능 관리 & v$sysstat
[2015-07-10-윤석준] Oracle 성능 관리 & v$sysstatSeok-joon Yun
 
[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4
[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4
[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4Seok-joon Yun
 

Mais de Seok-joon Yun (20)

Retrospective.2020 03
Retrospective.2020 03Retrospective.2020 03
Retrospective.2020 03
 
Sprint & Jira
Sprint & JiraSprint & Jira
Sprint & Jira
 
Eks.introduce.v2
Eks.introduce.v2Eks.introduce.v2
Eks.introduce.v2
 
Eks.introduce
Eks.introduceEks.introduce
Eks.introduce
 
AWS DEV DAY SEOUL 2017 Buliding Serverless Web App - 직방 Image Converter
AWS DEV DAY SEOUL 2017 Buliding Serverless Web App - 직방 Image ConverterAWS DEV DAY SEOUL 2017 Buliding Serverless Web App - 직방 Image Converter
AWS DEV DAY SEOUL 2017 Buliding Serverless Web App - 직방 Image Converter
 
아파트 시세,어쩌다 머신러닝까지
아파트 시세,어쩌다 머신러닝까지아파트 시세,어쩌다 머신러닝까지
아파트 시세,어쩌다 머신러닝까지
 
Pro typescript.ch07.Exception, Memory, Performance
Pro typescript.ch07.Exception, Memory, PerformancePro typescript.ch07.Exception, Memory, Performance
Pro typescript.ch07.Exception, Memory, Performance
 
Doing math with python.ch07
Doing math with python.ch07Doing math with python.ch07
Doing math with python.ch07
 
Doing math with python.ch06
Doing math with python.ch06Doing math with python.ch06
Doing math with python.ch06
 
Doing math with python.ch05
Doing math with python.ch05Doing math with python.ch05
Doing math with python.ch05
 
Doing math with python.ch04
Doing math with python.ch04Doing math with python.ch04
Doing math with python.ch04
 
Doing math with python.ch03
Doing math with python.ch03Doing math with python.ch03
Doing math with python.ch03
 
Doing mathwithpython.ch02
Doing mathwithpython.ch02Doing mathwithpython.ch02
Doing mathwithpython.ch02
 
Doing math with python.ch01
Doing math with python.ch01Doing math with python.ch01
Doing math with python.ch01
 
Pro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptPro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScript
 
C++ Concurrency in Action 9-2 Interrupting threads
C++ Concurrency in Action 9-2 Interrupting threadsC++ Concurrency in Action 9-2 Interrupting threads
C++ Concurrency in Action 9-2 Interrupting threads
 
Welcome to Modern C++
Welcome to Modern C++Welcome to Modern C++
Welcome to Modern C++
 
[2015-07-20-윤석준] Oracle 성능 관리 2
[2015-07-20-윤석준] Oracle 성능 관리 2[2015-07-20-윤석준] Oracle 성능 관리 2
[2015-07-20-윤석준] Oracle 성능 관리 2
 
[2015-07-10-윤석준] Oracle 성능 관리 & v$sysstat
[2015-07-10-윤석준] Oracle 성능 관리 & v$sysstat[2015-07-10-윤석준] Oracle 성능 관리 & v$sysstat
[2015-07-10-윤석준] Oracle 성능 관리 & v$sysstat
 
[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4
[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4
[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4
 

[C++ korea] effective modern c++ study item 17 19 신촌 study

  • 1. Effective Modern C++ Study C++ Korea Item 17 : Understand special member function generation. Item 18 : Use std::unique_ptr for exclusive-ownership resource management. Item 19 : Use std::shared_ptr for shared-ownership resource management .
  • 2.
  • 3. Effective Modern C++ Study C++ Korea3
  • 4. Effective Modern C++ Study C++ Korea4
  • 5. Effective Modern C++ Study C++ Korea5
  • 6. Effective Modern C++ Study C++ Korea6
  • 7. Effective Modern C++ Study C++ Korea7
  • 8. Effective Modern C++ Study C++ Korea8
  • 9. Effective Modern C++ Study C++ Korea9
  • 10. Effective Modern C++ Study C++ Korea10
  • 11.
  • 12. Effective Modern C++ Study C++ Korea12
  • 13. Effective Modern C++ Study C++ Korea13
  • 14. Effective Modern C++ Study C++ Korea14
  • 15. Effective Modern C++ Study C++ Korea15
  • 16. Effective Modern C++ Study C++ Korea16
  • 17. Effective Modern C++ Study C++ Korea17
  • 18. Effective Modern C++ Study C++ Korea18
  • 19. Effective Modern C++ Study C++ Korea19
  • 20. Effective Modern C++ Study C++ Korea20
  • 21. Effective Modern C++ Study C++ Korea21
  • 22. Effective Modern C++ Study C++ Korea22
  • 23. Effective Modern C++ Study C++ Korea23
  • 24. Effective Modern C++ Study C++ Korea24
  • 25. Effective Modern C++ Study C++ Korea25
  • 26. Effective Modern C++ Study C++ Korea26
  • 27. Effective Modern C++ Study C++ Korea27
  • 28. Effective Modern C++ Study C++ Korea28
  • 29. Effective Modern C++ Study C++ Korea29
  • 30. Effective Modern C++ Study C++ Korea30
  • 31. Effective Modern C++ Study C++ Korea31
  • 32. Effective Modern C++ Study C++ Korea32
  • 33. Effective Modern C++ Study C++ Korea33
  • 34. Effective Modern C++ Study C++ Korea34
  • 35.
  • 36.
  • 37.
  • 38. Effective Modern C++ Study C++ Korea38  1959년 LISP의 문제를 해결하기 위해 John McCarthy가 개발  Java, C#, 대부분의 Script 언어에서 쓰이고 있음  장점(버그를 줄이거나 완전히 막아줌) - 유효하지 않은 포인터에 접근 - 이중 해제 - Memory Leak  단점(주로 성능적 이슈) - GC 알고리즘의 오버헤드 (프로그래머는 빤히 아는데… 왜 그걸 굳이 또 계산해가면서…) - Timing 예측 불가 (중요한 타이밍에 버벅) - 자원해제 시점을 모른다. http://ko.wikipedia.org/wiki/쓰레기_수집_(컴퓨터_과학) GC의 장점 + !단점이 가능할까 ?
  • 39.
  • 40. Effective Modern C++ Study C++ Korea40 • 직접적으로 Object를 소유하지 않음 • 여러 개의 std::shared_ptr이 하나의 Object를 공유 • Object는 마지막 std::shared_ptr이 사라지면 해제 #include <memory> GC의 장점 : Object의 수명에 대해 신경 쓸 필요가 없다. !단점 : 원하는 시점에 해제가 가능하다. • 사용법은 생략 • 참조 사이트 : http://devluna.blogspot.kr/2014/12/stl-sharedptr-weakptr.html
  • 41.
  • 42. Effective Modern C++ Study C++ Korea42  해당 Object를 참조하고 있는 std::shared_ptr 의 개수  std::shared_ptr Constructor : Ref. Count ++  std::shared_ptr Destructor : Ref. Count - -  std::shared_ptr ::operator = : Left-hand Ref. Count ++, Right-hand Ref. Count - -  Atfer Ref. Count - - , if Ref. Count == 0 then delete object
  • 43. Effective Modern C++ Study C++ Korea43 1. Memory Issue • Raw Pointer 크기의 2배 : Object Pointer + Control Block Pointer (include Ref. Count) • Heap Memory (Dynamic Allocation) : Object 자체는 Ref. Count가 필요가 없다. 2. Performance Issue • Atomic 연산 (sizse는 word) • 대부분의 std::shared_ptr 은 Ref. Count ++ (Move 생성자, Move 연산자는 Ref. Count 변화 없음)
  • 44.
  • 45. Effective Modern C++ Study C++ Korea45 auto LogDel = [](T *pw) { makeLog(pw); delete pw; }; std::unique_ptr<T, decltype(LogDel)> UPW(new T, LogDel); // deleter type is part of ptr type std::shared_ptr<T> SPW(new T, LogDel); // deleter type is not part of ptr type - std::unique_ptr : template type의 부분 - std::shared_ptr : type의 일부가 아님 서로 다른 deleter를 가진 std::shared_ptr을 하나의 Container에 담을 수 있다.
  • 46. Effective Modern C++ Study C++ Korea46 - std::unique_ptr 은 custom deleter 크기를 포함 - std::shared_ptr 은 custom deleter 여부와 상관없이 무조건 Pointer 2개의 크기 • custom deleter는 function object 이다. • 그럼 어디 저장 될까 ? Control Block에 저장된다.
  • 47.
  • 48. Effective Modern C++ Study C++ Korea48 - Reference Count - Weak Count - Custom Deleter (if exists) - Allocator (if exists)
  • 49. Effective Modern C++ Study C++ Korea49 - std::make_shared - Unique-ownership Pointer (std::unique_ptr, std::auto_ptr)로 부터 std::shared_ptr 을 만들 때 - Raw Pointer로부터 std::shared_ptr 을 만들 때 OK OK (std::shared_ptr 로 부터 std::unique_ptr 는 불가능 하니깐) 가만 ! 딱 봐도 먼가 이상한 Smell 이…. 스멜스멜….
  • 50. Effective Modern C++ Study C++ Korea50 auto P = new T; { std::shared_ptr<T> SP1(P, makeLog); // create control block for *p { std::shared_ptr<T> SP2(P, makeLog);// create 2nd control block for *p } } 여기서 SP2의 Ref. Count == 0 이 되니, P의 dtor가 호출. 여기서 SP1의 Ref. Count == 0 이 되니, P의 dtor가 호출. 가만…. 이미 P는 해제됬는데… 아놔 어떡하지 ??? 1. Raw Pointer로 부터 std::shared_ptr을 생성하지 말자. (하지만, custom deleter를 사용할려면 std::make_shared를 사용 못하는데 ???) 2. 어쩔수 없다면 Raw Pointer를 변수에 담지말고 new로 생성한 R-Value를 사용 std::shared_ptr<T> SP(new T, LogDel); // direct use of new
  • 51.
  • 52. Effective Modern C++ Study C++ Korea52 std::vector<std::shared_ptr<T>> T_History; class T { public: void process(); }; void T::process() { T_History.emplace_back(this); // this is wrong } this는 Raw Pointer *this의 Control Block는 계속해서 만들어 질 것이다.
  • 53. Effective Modern C++ Study C++ Korea53 class T : public std::enable_shared_from_this<T> { public: void process(); }; void T::process() { T_History.emplace_back( shared_from_this() ); } 근데… 너 좀 낮설다. 파생 클래스에서 파생 클래스의 템플릿 클래스를 상속받는다 ? The Curiously Recurring Template Pattern (CRTP) this로부터 std::shared_ptr은 만들지만 Control Block은 안만든다. 그런데…. 만약 그전에 만들어진 Control Block이 없다면 ? 아놔~ 예외를 발생시킨다. 어떻하지 ???? Factory Method Pattern http://devluna.blogspot.kr/2015/01/factory-method-pattern.html
  • 54. Effective Modern C++ Study C++ Korea54 class T : public std::enable_shared_from_this<T> { public: template<typename... Ts> static std::shared_ptr<T> create(Ts&&... params); private: template<typename... Ts> T(Ts&&... params); }; 생성자를 private에 선언 Factory method에서 std::shared<T>를 return
  • 55.
  • 56. Effective Modern C++ Study C++ Korea56 • Dynamic Allocation • Size : few Words + custom deleter, allocator • Virtual Function • Atomic Calculation Default는 3 Words std::make_shared Object Destructor 1,2 Instruction Cycle 이정도 Cost만 감당한다면, 수명관리를 해준다.
  • 57.
  • 58. Effective Modern C++ Study C++ Korea58 • std::shared_ptr는 단일 Pointer에 대해서만 동작 • 그럼 delete[ ] 를 이용해서 custom deleter를 만들면 ? • std::shared_ptr에는 [ ] 연산자가 없다. • 결정적으로 단일 개체에 대해서만 derived-to-base 포인트 변환을 지원
  • 59.
  • 60. Effective Modern C++ Study C++ Korea60 • std::shared_ptr는 개체에 대한 수명관리를 Garbage Collection 만큼 편리하게 해준다. • std::unique_ptr에 비해 std::shared_ptr는 개체가 2배 더 크고, Control Block에 대한 오버해 드가 발생하고, Reference Count에 대해서 Atomic 연산을 해야 한다. • default 자원해제는 delete 지만 custom deleter도 지원한다. deleter의 타입은 std::shared_ptr 의 타입에 영향을 미치지 않는다. • Raw Pointer를 변수로 만들어서 std::shared_ptr로 만들지 마라.