SlideShare a Scribd company logo
Effective Modern C++ Study
C++ Korea
발표자 : 윤석준
Effective Modern C++ Study
C++ Korea
try
{
if (/* Exception Condition */)
throw new std::exception("Error Description");
}
catch (std::exception e)
{
cout << "Exception : " << e.what() << endl;
}
4
예외가 발생할 수 있는 부분을 정의
try { } 와 catch { } 는 한쌍
예외를 발생시킴
try 안에서 발생한 예외 중 e를 catch
예외 처리
Effective Modern C++ Study
C++ Korea5
• void func(int a)
• void func(int a) throw(int);
• void func(int a) throw(char *, int);
• void func(int a) throw();
모든 타입의 예외가 발생 가능하다.
int 타입 예외를 던질 수 있다.
타입이 2가지 이상일 경우는 , 로 나열
예외를 발생하지 않는다.
Effective Modern C++ Study
C++ Korea6
void f1() { throw 0; }
void f2() { f1(); }
void f3() { f2(); }
void f4() { f3(); }
void main()
{
try
{
f4();
}
catch (int e)
{
std::cout << e << std::endl;
}
}
 예외 처리를 하기 위해 발생 시점부터 처리하는 위치까지 Stack에서 함수를 소멸시키면서 이동
함수 호출
스택 풀기
http://devluna.blogspot.kr/2015/02/c-exception-handling.html
Effective Modern C++ Study
C++ Korea8
 사용자는 자신이 사용 하는 함수의 발생 가능한 예외들에 대해서 알고 있어야 한다.
 하지만 C++에서는 상당히 귀찮은 일이고 그 동안 잘 안 했었다.
 기껏해야 예외를 발생하지 않을 경우만 명시적으로 선언해주는 친절한 사람도
간혹 있긴 하더라고 누군가 말하는걸 얼핏 들은 적이라도 있나 ?
(난 없음)
int f(int x) throw(); // C++98 Style
int f(int x) noexcept; // C++11 Style
Effective Modern C++ Study
C++ Korea9
• C++98 Style : 스택 풀기(Stack unwinding)을 시도
• C++11 Style : 스택 풀기를 프로그램 종료전에 할 수도 있다.
(gcc는 하지않고 종료, Clang은 종료전에 스택 풀기 수행)
• noexcept를 쓰면 예외가 전파되는 동안 Runtime 스택을 유지할 필요도 없고,
함수내 생성한 객체도 순서에 상관없이 소멸이 가능하다.
int f(int x) noexcept; // most optimizable
int f(int x) throw(); // less optimizable
int f(int x); // less optimizable
Effective Modern C++ Study
C++ Korea10
• Push를 하려는데 내부 버퍼가 꽉찼다면 ?
1. 크기를 2배로 확장
2. Data COPY
3. 기존 공간 삭제
4. 객체가 가리키는 주소 변경
std::vector<Widget> vw;
Widget w;
vw.push_back(w);
• 어~~~~ 그런데~~~~~
COPY 중 오류가 나면 ???
1. 그냥 기존꺼 쓰면 되지머.
2. 끝 !
Effective Modern C++ Study
C++ Korea11
• Push를 하려는데 내부 버퍼가 꽉찼다면 ?
1. 크기를 2배로 확장
2. Data MOVE
3. 기존 공간 삭제
4. 객체가 가리키는 주소 변경
• 어~~~~ 그런데~~~~~
MOVE 중 오류가 나면 ???
1. 다시 원래대로 MOVE 하자.
• 어~ 다시 MOVE 하는데 오류가 ?
아놔~
std::vector<Widget> vw;
Widget w;
vw.push_back(w);
Effective Modern C++ Study
C++ Korea12
• 그럼 MOVE 하지 말고 C++ 98 Style로 COPY를 ?
• 예외가 안 일어난다고 확인된 것만 MOVE 하자.
• 예외가 일어날지 안 일어날지는 어떻게 알고 ?
• noexcept 라고 선언된 것만 MOVE 하자.
Effective Modern C++ Study
C++ Korea13
noexcept(bool expr = true)
template <class T, size_t N>
void swap(T(&a)[N],
T(&b)[N]) noexcept(noexcept(swap(*a, *b)));
template <class T1, class T2>
struct pair {
...
void swap(pair& p) noexcept(noexcept(swap(first, p.first)) &&
noexcept(swap(second, p.second)));
...
};
배열의 각 요소들의 swap이
noexcept인 경우 해당 함수도
noexcept
pair의 각 요소들의 swap이
noexcept인 경우 해당 함수도
noexcept
Effective Modern C++ Study
C++ Korea15
 noexcept는 심사 숙고해서 사용하자.
noexcept로 선언한 함수를 수정하였는데 예외가 발생할 수 있게 되었다면 ???
noexcept지우면 되지머.
그럼 noexcept라고 믿고 해당 함수를 쓴 code들은 ???
흠… 난리나겠네. ;;;;
예외가 안나오도록 안에서 어떻게든 다 처리하지머.
noexcept를 쓰는 이유가 성능상 이익을 보기 위해서인데… 이러면…
아고… 의미없다.
그럼 예외가 아니라 return값으로 error code들을 처리하면 ???
성능상 이익이라고 아까 말했는데, 이러면 함수를 사용한 쪽에서 다시 해석을 해야하고…
Effective Modern C++ Study
C++ Korea16
• default로 noexcept 의 특성을 가지는 대표적인 예
• 멤버 변수의 소멸자가 모두 noexcept일 경우 자동으로 noexcept로 처리
(STL내에는 예외 발생 가능한 소멸자는 없다.)
• 예외가 발생할 수 있을 경우는 명시적으로 noexcept(false)로 선언
Effective Modern C++ Study
C++ Korea17
• Wide contracts : 함수 호출 전 사전 조건이 없음
void f(const std::string& s) noexcept; // precontidion : s.length() <= 32
• Narrow contracts : 함수 호출 전 사전 조건이 있음
Precondition violation exception 을 발생시켜야 한다.
Effective Modern C++ Study
C++ Korea18
void setup();
void cleanup();
void init() noexcept
{
setup();
// do something
cleanup();
}• C-Style 함수
• C++98 이전에 개발된 함수
일수도 있으므로, noexcept 여부를 Check하지 않는다.
noexcept 선언이 없는데…
Effective Modern C++ Study
C++ Korea20
• noexcept는 함수 인터페이스에 속한다. 해당 함수 사용자는 noexcept 여부에 대해서 알아야 한다.
• noexcept로 함수를 선언하면 성능상의 이점을 볼 수 있다.
• move 연산, swap, 메모리 해제 함수, 소멸자 등에서의 noexcept 여부는 아주 중요하다.
• 대부분의 함수들은 noexcept로 선언하지 않고 예외를 처리하는 함수로 선언하는게 더 자연스럽다.
http://devluna.blogspot.kr/2015/02/item-14-noexcept.html
icysword77@gmail.com

More Related Content

What's hot

emc++ chapter32
emc++ chapter32emc++ chapter32
emc++ chapter32
Tatsuki SHIMIZU
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by Example
Olve Maudal
 
Effective Modern C++ 勉強会#1 Item3,4
Effective Modern C++ 勉強会#1 Item3,4Effective Modern C++ 勉強会#1 Item3,4
Effective Modern C++ 勉強会#1 Item3,4
Takashi Hoshino
 
[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
Chris Ohk
 
組み込みでこそC++を使う10の理由
組み込みでこそC++を使う10の理由組み込みでこそC++を使う10の理由
組み込みでこそC++を使う10の理由kikairoya
 
Chapitre6: Surcharge des opérateurs
Chapitre6:  Surcharge des opérateursChapitre6:  Surcharge des opérateurs
Chapitre6: Surcharge des opérateurs
Aziz Darouichi
 
CPP Language Basics - Reference
CPP Language Basics - ReferenceCPP Language Basics - Reference
CPP Language Basics - Reference
Mohammed Sikander
 
Emcpp0506
Emcpp0506Emcpp0506
Emcpp0506
Takatoshi Kondo
 
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
Chris Ohk
 
Emcpp item31
Emcpp item31Emcpp item31
Emcpp item31
mitsutaka_takeda
 
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.
 
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
Chris Ohk
 
BoostAsioで可読性を求めるのは間違っているだろうか
BoostAsioで可読性を求めるのは間違っているだろうかBoostAsioで可読性を求めるのは間違っているだろうか
BoostAsioで可読性を求めるのは間違っているだろうか
Yuki Miyatake
 
Boost.Coroutine
Boost.CoroutineBoost.Coroutine
Boost.Coroutinemelpon
 
Arrays in c unit iii chapter 1 mrs.sowmya jyothi
Arrays in c unit iii chapter 1 mrs.sowmya jyothiArrays in c unit iii chapter 1 mrs.sowmya jyothi
Arrays in c unit iii chapter 1 mrs.sowmya jyothi
Sowmya Jyothi
 
Effective Modern C++勉強会#4 Item 17, 18資料
Effective Modern C++勉強会#4 Item 17, 18資料Effective Modern C++勉強会#4 Item 17, 18資料
Effective Modern C++勉強会#4 Item 17, 18資料
Ryo Igarashi
 
C#や.NET Frameworkがやっていること
C#や.NET FrameworkがやっていることC#や.NET Frameworkがやっていること
C#や.NET Frameworkがやっていること
信之 岩永
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
Vineeta Garg
 
Poo en c++ les relations entre classes
Poo en c++ les relations entre classesPoo en c++ les relations entre classes
Poo en c++ les relations entre classes
Amina HAMEURLAINE
 

What's hot (20)

emc++ chapter32
emc++ chapter32emc++ chapter32
emc++ chapter32
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by Example
 
Effective Modern C++ 勉強会#1 Item3,4
Effective Modern C++ 勉強会#1 Item3,4Effective Modern C++ 勉強会#1 Item3,4
Effective Modern C++ 勉強会#1 Item3,4
 
Chap 6(decision making-looping)
Chap 6(decision making-looping)Chap 6(decision making-looping)
Chap 6(decision making-looping)
 
[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
 
組み込みでこそC++を使う10の理由
組み込みでこそC++を使う10の理由組み込みでこそC++を使う10の理由
組み込みでこそC++を使う10の理由
 
Chapitre6: Surcharge des opérateurs
Chapitre6:  Surcharge des opérateursChapitre6:  Surcharge des opérateurs
Chapitre6: Surcharge des opérateurs
 
CPP Language Basics - Reference
CPP Language Basics - ReferenceCPP Language Basics - Reference
CPP Language Basics - Reference
 
Emcpp0506
Emcpp0506Emcpp0506
Emcpp0506
 
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
 
Emcpp item31
Emcpp item31Emcpp item31
Emcpp item31
 
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)
 
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
 
BoostAsioで可読性を求めるのは間違っているだろうか
BoostAsioで可読性を求めるのは間違っているだろうかBoostAsioで可読性を求めるのは間違っているだろうか
BoostAsioで可読性を求めるのは間違っているだろうか
 
Boost.Coroutine
Boost.CoroutineBoost.Coroutine
Boost.Coroutine
 
Arrays in c unit iii chapter 1 mrs.sowmya jyothi
Arrays in c unit iii chapter 1 mrs.sowmya jyothiArrays in c unit iii chapter 1 mrs.sowmya jyothi
Arrays in c unit iii chapter 1 mrs.sowmya jyothi
 
Effective Modern C++勉強会#4 Item 17, 18資料
Effective Modern C++勉強会#4 Item 17, 18資料Effective Modern C++勉強会#4 Item 17, 18資料
Effective Modern C++勉強会#4 Item 17, 18資料
 
C#や.NET Frameworkがやっていること
C#や.NET FrameworkがやっていることC#や.NET Frameworkがやっていること
C#や.NET Frameworkがやっていること
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
Poo en c++ les relations entre classes
Poo en c++ les relations entre classesPoo en c++ les relations entre classes
Poo en c++ les relations entre classes
 

Viewers also liked

[C++ korea] effective modern c++ study item 3 understand decltype +이동우
[C++ korea] effective modern c++ study   item 3 understand decltype +이동우[C++ korea] effective modern c++ study   item 3 understand decltype +이동우
[C++ korea] effective modern c++ study item 3 understand decltype +이동우
Seok-joon Yun
 
[C++ korea] effective modern c++ study item 4 - 6 신촌
[C++ korea] effective modern c++ study   item 4 - 6 신촌[C++ korea] effective modern c++ study   item 4 - 6 신촌
[C++ korea] effective modern c++ study item 4 - 6 신촌
Seok-joon Yun
 
기업을 위한 Google drive 100% 활용 백서
기업을 위한 Google drive 100% 활용 백서기업을 위한 Google drive 100% 활용 백서
기업을 위한 Google drive 100% 활용 백서
CharlyChoi
 
[C++ korea] effective modern c++ study item 7 distinguish between () and {} w...
[C++ korea] effective modern c++ study item 7 distinguish between () and {} w...[C++ korea] effective modern c++ study item 7 distinguish between () and {} w...
[C++ korea] effective modern c++ study item 7 distinguish between () and {} w...
Seok-joon Yun
 
[C++ Korea] Effective Modern C++ MVA item 8 Prefer nullptr to 0 and null +윤석준
[C++ Korea] Effective Modern C++ MVA item 8 Prefer nullptr to 0 and null +윤석준[C++ Korea] Effective Modern C++ MVA item 8 Prefer nullptr to 0 and null +윤석준
[C++ Korea] Effective Modern C++ MVA item 8 Prefer nullptr to 0 and null +윤석준
Seok-joon Yun
 
[C++ Korea] Effective Modern C++ MVA item 9 Prefer alias declarations to type...
[C++ Korea] Effective Modern C++ MVA item 9 Prefer alias declarations to type...[C++ Korea] Effective Modern C++ MVA item 9 Prefer alias declarations to type...
[C++ Korea] Effective Modern C++ MVA item 9 Prefer alias declarations to type...
Seok-joon Yun
 
[C++ korea] effective modern c++ study item8~10 정은식
[C++ korea] effective modern c++ study item8~10 정은식[C++ korea] effective modern c++ study item8~10 정은식
[C++ korea] effective modern c++ study item8~10 정은식
은식 정
 
Effective C++ Chaper 1
Effective C++ Chaper 1Effective C++ Chaper 1
Effective C++ Chaper 1
연우 김
 
[1116 박민근] c++11에 추가된 새로운 기능들
[1116 박민근] c++11에 추가된 새로운 기능들[1116 박민근] c++11에 추가된 새로운 기능들
[1116 박민근] c++11에 추가된 새로운 기능들MinGeun Park
 
[Td 2015]디버깅, 어디까지 해봤니 당신이 아마도 몰랐을 디버깅 꿀팁 공개(김희준)
[Td 2015]디버깅, 어디까지 해봤니 당신이 아마도 몰랐을 디버깅 꿀팁 공개(김희준)[Td 2015]디버깅, 어디까지 해봤니 당신이 아마도 몰랐을 디버깅 꿀팁 공개(김희준)
[Td 2015]디버깅, 어디까지 해봤니 당신이 아마도 몰랐을 디버깅 꿀팁 공개(김희준)
Sang Don Kim
 

Viewers also liked (10)

[C++ korea] effective modern c++ study item 3 understand decltype +이동우
[C++ korea] effective modern c++ study   item 3 understand decltype +이동우[C++ korea] effective modern c++ study   item 3 understand decltype +이동우
[C++ korea] effective modern c++ study item 3 understand decltype +이동우
 
[C++ korea] effective modern c++ study item 4 - 6 신촌
[C++ korea] effective modern c++ study   item 4 - 6 신촌[C++ korea] effective modern c++ study   item 4 - 6 신촌
[C++ korea] effective modern c++ study item 4 - 6 신촌
 
기업을 위한 Google drive 100% 활용 백서
기업을 위한 Google drive 100% 활용 백서기업을 위한 Google drive 100% 활용 백서
기업을 위한 Google drive 100% 활용 백서
 
[C++ korea] effective modern c++ study item 7 distinguish between () and {} w...
[C++ korea] effective modern c++ study item 7 distinguish between () and {} w...[C++ korea] effective modern c++ study item 7 distinguish between () and {} w...
[C++ korea] effective modern c++ study item 7 distinguish between () and {} w...
 
[C++ Korea] Effective Modern C++ MVA item 8 Prefer nullptr to 0 and null +윤석준
[C++ Korea] Effective Modern C++ MVA item 8 Prefer nullptr to 0 and null +윤석준[C++ Korea] Effective Modern C++ MVA item 8 Prefer nullptr to 0 and null +윤석준
[C++ Korea] Effective Modern C++ MVA item 8 Prefer nullptr to 0 and null +윤석준
 
[C++ Korea] Effective Modern C++ MVA item 9 Prefer alias declarations to type...
[C++ Korea] Effective Modern C++ MVA item 9 Prefer alias declarations to type...[C++ Korea] Effective Modern C++ MVA item 9 Prefer alias declarations to type...
[C++ Korea] Effective Modern C++ MVA item 9 Prefer alias declarations to type...
 
[C++ korea] effective modern c++ study item8~10 정은식
[C++ korea] effective modern c++ study item8~10 정은식[C++ korea] effective modern c++ study item8~10 정은식
[C++ korea] effective modern c++ study item8~10 정은식
 
Effective C++ Chaper 1
Effective C++ Chaper 1Effective C++ Chaper 1
Effective C++ Chaper 1
 
[1116 박민근] c++11에 추가된 새로운 기능들
[1116 박민근] c++11에 추가된 새로운 기능들[1116 박민근] c++11에 추가된 새로운 기능들
[1116 박민근] c++11에 추가된 새로운 기능들
 
[Td 2015]디버깅, 어디까지 해봤니 당신이 아마도 몰랐을 디버깅 꿀팁 공개(김희준)
[Td 2015]디버깅, 어디까지 해봤니 당신이 아마도 몰랐을 디버깅 꿀팁 공개(김희준)[Td 2015]디버깅, 어디까지 해봤니 당신이 아마도 몰랐을 디버깅 꿀팁 공개(김희준)
[Td 2015]디버깅, 어디까지 해봤니 당신이 아마도 몰랐을 디버깅 꿀팁 공개(김희준)
 

Similar to [C++ korea] effective modern c++ study item 14 declare functions noexcept if they won't emit exceptions +윤석준

Effective modern cpp item14
Effective modern cpp item14Effective modern cpp item14
Effective modern cpp item14
진화 손
 
[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
Chris Ohk
 
[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
 
Effective c++ chapter1 2_dcshin
Effective c++ chapter1 2_dcshinEffective c++ chapter1 2_dcshin
Effective c++ chapter1 2_dcshin
Dong Chan Shin
 
HI-ARC PS 101
HI-ARC PS 101HI-ARC PS 101
HI-ARC PS 101
Jae-yeol Lee
 
C++20 Key Features Summary
C++20 Key Features SummaryC++20 Key Features Summary
C++20 Key Features Summary
Chris Ohk
 
불어오는 변화의 바람, 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
명신 김
 
Exception&log
Exception&logException&log
Exception&log
Nam Hyeonuk
 
Changes in c++0x
Changes in c++0xChanges in c++0x
Changes in c++0x
Sang Yeon Jeon
 
모던 C++ 정리
모던 C++ 정리모던 C++ 정리
모던 C++ 정리
Hansol Kang
 
Effective c++ chapter 1,2 요약
Effective c++ chapter 1,2 요약Effective c++ chapter 1,2 요약
Effective c++ chapter 1,2 요약
Nam Hyeonuk
 
2013 C++ Study For Students #1
2013 C++ Study For Students #12013 C++ Study For Students #1
2013 C++ Study For Students #1
Chris Ohk
 
카사 공개세미나1회 W.E.L.C.
카사 공개세미나1회  W.E.L.C.카사 공개세미나1회  W.E.L.C.
카사 공개세미나1회 W.E.L.C.Ryan Park
 
About Visual C++ 10
About  Visual C++ 10About  Visual C++ 10
About Visual C++ 10
흥배 최
 
Modern C++의 타입 추론과 람다, 컨셉
Modern C++의 타입 추론과 람다, 컨셉Modern C++의 타입 추론과 람다, 컨셉
Modern C++의 타입 추론과 람다, 컨셉
HyunJoon Park
 
GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)
GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)
GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)
Kyoungchan Lee
 
Let's Go (golang)
Let's Go (golang)Let's Go (golang)
Let's Go (golang)
상욱 송
 
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
 
C Language For Arduino
C Language For ArduinoC Language For Arduino
C Language For Arduino
영욱 김
 
A tour of C++ : the basics
A tour of C++ : the basicsA tour of C++ : the basics
A tour of C++ : the basics
Jaewon Choi
 

Similar to [C++ korea] effective modern c++ study item 14 declare functions noexcept if they won't emit exceptions +윤석준 (20)

Effective modern cpp item14
Effective modern cpp item14Effective modern cpp item14
Effective modern cpp item14
 
[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++ 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...
 
Effective c++ chapter1 2_dcshin
Effective c++ chapter1 2_dcshinEffective c++ chapter1 2_dcshin
Effective c++ chapter1 2_dcshin
 
HI-ARC PS 101
HI-ARC PS 101HI-ARC PS 101
HI-ARC PS 101
 
C++20 Key Features Summary
C++20 Key Features SummaryC++20 Key Features Summary
C++20 Key Features Summary
 
불어오는 변화의 바람, 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
 
Exception&log
Exception&logException&log
Exception&log
 
Changes in c++0x
Changes in c++0xChanges in c++0x
Changes in c++0x
 
모던 C++ 정리
모던 C++ 정리모던 C++ 정리
모던 C++ 정리
 
Effective c++ chapter 1,2 요약
Effective c++ chapter 1,2 요약Effective c++ chapter 1,2 요약
Effective c++ chapter 1,2 요약
 
2013 C++ Study For Students #1
2013 C++ Study For Students #12013 C++ Study For Students #1
2013 C++ Study For Students #1
 
카사 공개세미나1회 W.E.L.C.
카사 공개세미나1회  W.E.L.C.카사 공개세미나1회  W.E.L.C.
카사 공개세미나1회 W.E.L.C.
 
About Visual C++ 10
About  Visual C++ 10About  Visual C++ 10
About Visual C++ 10
 
Modern C++의 타입 추론과 람다, 컨셉
Modern C++의 타입 추론과 람다, 컨셉Modern C++의 타입 추론과 람다, 컨셉
Modern C++의 타입 추론과 람다, 컨셉
 
GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)
GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)
GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)
 
Let's Go (golang)
Let's Go (golang)Let's Go (golang)
Let's Go (golang)
 
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 ...
 
C Language For Arduino
C Language For ArduinoC Language For Arduino
C Language For Arduino
 
A tour of C++ : the basics
A tour of C++ : the basicsA tour of C++ : the basics
A tour of C++ : the basics
 

More from Seok-joon Yun

Retrospective.2020 03
Retrospective.2020 03Retrospective.2020 03
Retrospective.2020 03
Seok-joon Yun
 
Sprint & Jira
Sprint & JiraSprint & Jira
Sprint & Jira
Seok-joon Yun
 
Eks.introduce.v2
Eks.introduce.v2Eks.introduce.v2
Eks.introduce.v2
Seok-joon Yun
 
Eks.introduce
Eks.introduceEks.introduce
Eks.introduce
Seok-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 Converter
Seok-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, Performance
Seok-joon Yun
 
Doing math with python.ch07
Doing math with python.ch07Doing math with python.ch07
Doing math with python.ch07
Seok-joon Yun
 
Doing math with python.ch06
Doing math with python.ch06Doing math with python.ch06
Doing math with python.ch06
Seok-joon Yun
 
Doing math with python.ch05
Doing math with python.ch05Doing math with python.ch05
Doing math with python.ch05
Seok-joon Yun
 
Doing math with python.ch04
Doing math with python.ch04Doing math with python.ch04
Doing math with python.ch04
Seok-joon Yun
 
Doing math with python.ch03
Doing math with python.ch03Doing math with python.ch03
Doing math with python.ch03
Seok-joon Yun
 
Doing mathwithpython.ch02
Doing mathwithpython.ch02Doing mathwithpython.ch02
Doing mathwithpython.ch02
Seok-joon Yun
 
Doing math with python.ch01
Doing math with python.ch01Doing math with python.ch01
Doing math with python.ch01
Seok-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 TypeScript
Seok-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 threads
Seok-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 성능 관리 2
Seok-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$sysstat
Seok-joon Yun
 
[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4
[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4
[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4Seok-joon Yun
 

More from 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 14 declare functions noexcept if they won't emit exceptions +윤석준

  • 1. Effective Modern C++ Study C++ Korea 발표자 : 윤석준
  • 2.
  • 3.
  • 4. Effective Modern C++ Study C++ Korea try { if (/* Exception Condition */) throw new std::exception("Error Description"); } catch (std::exception e) { cout << "Exception : " << e.what() << endl; } 4 예외가 발생할 수 있는 부분을 정의 try { } 와 catch { } 는 한쌍 예외를 발생시킴 try 안에서 발생한 예외 중 e를 catch 예외 처리
  • 5. Effective Modern C++ Study C++ Korea5 • void func(int a) • void func(int a) throw(int); • void func(int a) throw(char *, int); • void func(int a) throw(); 모든 타입의 예외가 발생 가능하다. int 타입 예외를 던질 수 있다. 타입이 2가지 이상일 경우는 , 로 나열 예외를 발생하지 않는다.
  • 6. Effective Modern C++ Study C++ Korea6 void f1() { throw 0; } void f2() { f1(); } void f3() { f2(); } void f4() { f3(); } void main() { try { f4(); } catch (int e) { std::cout << e << std::endl; } }  예외 처리를 하기 위해 발생 시점부터 처리하는 위치까지 Stack에서 함수를 소멸시키면서 이동 함수 호출 스택 풀기 http://devluna.blogspot.kr/2015/02/c-exception-handling.html
  • 7.
  • 8. Effective Modern C++ Study C++ Korea8  사용자는 자신이 사용 하는 함수의 발생 가능한 예외들에 대해서 알고 있어야 한다.  하지만 C++에서는 상당히 귀찮은 일이고 그 동안 잘 안 했었다.  기껏해야 예외를 발생하지 않을 경우만 명시적으로 선언해주는 친절한 사람도 간혹 있긴 하더라고 누군가 말하는걸 얼핏 들은 적이라도 있나 ? (난 없음) int f(int x) throw(); // C++98 Style int f(int x) noexcept; // C++11 Style
  • 9. Effective Modern C++ Study C++ Korea9 • C++98 Style : 스택 풀기(Stack unwinding)을 시도 • C++11 Style : 스택 풀기를 프로그램 종료전에 할 수도 있다. (gcc는 하지않고 종료, Clang은 종료전에 스택 풀기 수행) • noexcept를 쓰면 예외가 전파되는 동안 Runtime 스택을 유지할 필요도 없고, 함수내 생성한 객체도 순서에 상관없이 소멸이 가능하다. int f(int x) noexcept; // most optimizable int f(int x) throw(); // less optimizable int f(int x); // less optimizable
  • 10. Effective Modern C++ Study C++ Korea10 • Push를 하려는데 내부 버퍼가 꽉찼다면 ? 1. 크기를 2배로 확장 2. Data COPY 3. 기존 공간 삭제 4. 객체가 가리키는 주소 변경 std::vector<Widget> vw; Widget w; vw.push_back(w); • 어~~~~ 그런데~~~~~ COPY 중 오류가 나면 ??? 1. 그냥 기존꺼 쓰면 되지머. 2. 끝 !
  • 11. Effective Modern C++ Study C++ Korea11 • Push를 하려는데 내부 버퍼가 꽉찼다면 ? 1. 크기를 2배로 확장 2. Data MOVE 3. 기존 공간 삭제 4. 객체가 가리키는 주소 변경 • 어~~~~ 그런데~~~~~ MOVE 중 오류가 나면 ??? 1. 다시 원래대로 MOVE 하자. • 어~ 다시 MOVE 하는데 오류가 ? 아놔~ std::vector<Widget> vw; Widget w; vw.push_back(w);
  • 12. Effective Modern C++ Study C++ Korea12 • 그럼 MOVE 하지 말고 C++ 98 Style로 COPY를 ? • 예외가 안 일어난다고 확인된 것만 MOVE 하자. • 예외가 일어날지 안 일어날지는 어떻게 알고 ? • noexcept 라고 선언된 것만 MOVE 하자.
  • 13. Effective Modern C++ Study C++ Korea13 noexcept(bool expr = true) template <class T, size_t N> void swap(T(&a)[N], T(&b)[N]) noexcept(noexcept(swap(*a, *b))); template <class T1, class T2> struct pair { ... void swap(pair& p) noexcept(noexcept(swap(first, p.first)) && noexcept(swap(second, p.second))); ... }; 배열의 각 요소들의 swap이 noexcept인 경우 해당 함수도 noexcept pair의 각 요소들의 swap이 noexcept인 경우 해당 함수도 noexcept
  • 14.
  • 15. Effective Modern C++ Study C++ Korea15  noexcept는 심사 숙고해서 사용하자. noexcept로 선언한 함수를 수정하였는데 예외가 발생할 수 있게 되었다면 ??? noexcept지우면 되지머. 그럼 noexcept라고 믿고 해당 함수를 쓴 code들은 ??? 흠… 난리나겠네. ;;;; 예외가 안나오도록 안에서 어떻게든 다 처리하지머. noexcept를 쓰는 이유가 성능상 이익을 보기 위해서인데… 이러면… 아고… 의미없다. 그럼 예외가 아니라 return값으로 error code들을 처리하면 ??? 성능상 이익이라고 아까 말했는데, 이러면 함수를 사용한 쪽에서 다시 해석을 해야하고…
  • 16. Effective Modern C++ Study C++ Korea16 • default로 noexcept 의 특성을 가지는 대표적인 예 • 멤버 변수의 소멸자가 모두 noexcept일 경우 자동으로 noexcept로 처리 (STL내에는 예외 발생 가능한 소멸자는 없다.) • 예외가 발생할 수 있을 경우는 명시적으로 noexcept(false)로 선언
  • 17. Effective Modern C++ Study C++ Korea17 • Wide contracts : 함수 호출 전 사전 조건이 없음 void f(const std::string& s) noexcept; // precontidion : s.length() <= 32 • Narrow contracts : 함수 호출 전 사전 조건이 있음 Precondition violation exception 을 발생시켜야 한다.
  • 18. Effective Modern C++ Study C++ Korea18 void setup(); void cleanup(); void init() noexcept { setup(); // do something cleanup(); }• C-Style 함수 • C++98 이전에 개발된 함수 일수도 있으므로, noexcept 여부를 Check하지 않는다. noexcept 선언이 없는데…
  • 19.
  • 20. Effective Modern C++ Study C++ Korea20 • noexcept는 함수 인터페이스에 속한다. 해당 함수 사용자는 noexcept 여부에 대해서 알아야 한다. • noexcept로 함수를 선언하면 성능상의 이점을 볼 수 있다. • move 연산, swap, 메모리 해제 함수, 소멸자 등에서의 noexcept 여부는 아주 중요하다. • 대부분의 함수들은 noexcept로 선언하지 않고 예외를 처리하는 함수로 선언하는게 더 자연스럽다.