SlideShare a Scribd company logo
1 of 16
Download to read offline
Item 14. 예외를 방출하지 않을
함수는 noexcept로 선언하라
Effective Modern C++ 스터디
이데아 게임즈 손진화
예외 명세(exception specification)
• 함수를 호출할 때 사용자는 호출하는 함수가
어떤 예외를 발생시키는지 알아야 한다
• C++11에서는 사용하는 함수가 예외를 발생
시키지 않을 수 있다고 보장 할 경우
noexcept 키워드를 사용할 수 있다
예외를 발생시키지 않는 함수
• int f(int x) throw() // C++ 98
• Int f(int x) noexcept // C++ 11
만약 에러가 났을 경우
• throw() // C++ 98
스택 풀기(stack unwind)를 시도하다가 에러 처리
코드를 만나지 못하면 실행이 종료된다
• noexcept
- 스택 풀기 수행 여부는 컴파일러마다 다르다
- VS 에서는 에러 처리 코드가 있어도 프로그램이
종료된다
최적화 정도
• Int f(int x) noexcept
최적화 여지가 가장 크다
• int f(int x) throw()
최적화 여지가 더 작다
• int f(int x)
최적화 여지가 더 작다
예제
std::vector<Widget> vw;
Widget w;
vw.push_back(w);
• 이 때 vw의 용량이 넘어 갈 경우 새 벡터를 만
들고 요소들을 복사하고 기존 객체들을 파괴
하여 작업을 완료한다
• 중간에 오류가 나도 안전하다
예제
std::vector<Widget> vw;
Widget w;
vw.push_back(w);
• 이 때 vw의 용량이 넘어 갈 경우 새 벡터를 만
들고 요소들을 이동하여 작업을 완료한다
• 중간에 오류가 나면 망한다
• 오류가 발생하지 않는다면 성능향상을 기대
예제 - 해결
• 예외 발생이 가능한 경우는 move대신 copy
를 한다
• 예외가 발생하지 않는다고 확인되면 move를
사용한다
• 예외 발생 여부는 noexcept 키워드로
지정하면 된다
예제 - 해결
• C++98에서 강한 예외 안전성을 보장하는 함
수들 중에 이런 식으로 동작하는 함수들은 모
두 C++11에서 이렇게 동작하도록 수정되었
다
• std::vector::reserve
std::vector::insert
td::deque::insert
조건부 noexcept
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)));
...
}; // throw() 보다 좋아졌다!
noexcept 를 잘 생각하고 사용하자
• noexcept 함수 였다가 후에 바뀌는 경우
• 예외 중립적 함수인 경우
• noexcept를 쓰기 위해 함수 내부에서
예외처리 등을 많이 해두어서 성능상 이득을
못 보는 경우
noexcept 를 잘 생각하고 사용하자
• 메모리 해제 함수와 모든 소멸자는 암묵적으
로 noexcept로 선언된다
만약에 바꾸고 싶은 경우 noexcept(false)
사용
• 넓은 계약을 가진 함수들에 대해서만
noexcept 키워드를 사용
void f(const std::string& s) noexcept;
// 전제조건 : s.length() <= 32
넓은 계약, 좁은 계약
• 넓은 계약
함수를 호출하기 위한 사전 조건이 존재하지
않는다.
• 좁은 계약
넓은 계약을 만족하지 못하는 모든 경우
• 미정의 행동
하지 말라는 행동..
noexcept 를 잘 생각하고 사용하자
• 함수 구현과 예외 명세 사이를 컴파일러가
파악해주지 않는다
void setup();
void cleanup();
void init() noexcept
{
setup();
// …
cleanup();
} // ok
결론
• noexcept는 함수의 인터페이스의 일부이다
이는 호출자가 noexcept 여부에 의존할 수
있음을 뜻한다
• noexcept 함수는 비noexcept함수보다
최적화의 여지가 크다
결론
• noexcept는 이동 연산들과 swap,
메모리 해제 함수들, 그리고 소멸자들에
특히나 유용하다
• 대부분의 함수는 noexcept가 아니라 예외에
중립적이다

More Related Content

What's hot

[KOSSA] C++ Programming - 13th Study - exception handling
[KOSSA] C++ Programming - 13th Study - exception handling[KOSSA] C++ Programming - 13th Study - exception handling
[KOSSA] C++ Programming - 13th Study - exception handlingSeok-joon Yun
 
[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
 
Startup JavaScript 3 - 조건문, 반복문, 예외처리
Startup JavaScript 3 - 조건문, 반복문, 예외처리Startup JavaScript 3 - 조건문, 반복문, 예외처리
Startup JavaScript 3 - 조건문, 반복문, 예외처리Circulus
 
코딩인카페 C&JAVA 기초과정 C프로그래밍(1)
코딩인카페 C&JAVA 기초과정 C프로그래밍(1)코딩인카페 C&JAVA 기초과정 C프로그래밍(1)
코딩인카페 C&JAVA 기초과정 C프로그래밍(1)유익아카데미
 
[C++ korea] effective modern c++ study item 14 declare functions noexcept if ...
[C++ korea] effective modern c++ study item 14 declare functions noexcept if ...[C++ korea] effective modern c++ study item 14 declare functions noexcept if ...
[C++ korea] effective modern c++ study item 14 declare functions noexcept if ...Seok-joon Yun
 
[2012 CodeEngn Conference 07] manGoo - Exploit Writing Technique의 발전과 최신 트랜드
[2012 CodeEngn Conference 07] manGoo - Exploit Writing Technique의 발전과 최신 트랜드[2012 CodeEngn Conference 07] manGoo - Exploit Writing Technique의 발전과 최신 트랜드
[2012 CodeEngn Conference 07] manGoo - Exploit Writing Technique의 발전과 최신 트랜드GangSeok Lee
 
[C++ korea] Effective Modern C++ 신촌 Study Item20,21,23
[C++ korea] Effective Modern C++ 신촌 Study Item20,21,23[C++ korea] Effective Modern C++ 신촌 Study Item20,21,23
[C++ korea] Effective Modern C++ 신촌 Study Item20,21,23Seok-joon Yun
 
코딩인카페 C&JAVA 기초과정 C프로그래밍(3)
코딩인카페 C&JAVA 기초과정 C프로그래밍(3)코딩인카페 C&JAVA 기초과정 C프로그래밍(3)
코딩인카페 C&JAVA 기초과정 C프로그래밍(3)유익아카데미
 
[명우니닷컴] 2번째 숙제 - 두 정수의 연산 (공연 예약 시스템)
[명우니닷컴] 2번째 숙제 - 두 정수의 연산 (공연 예약 시스템)[명우니닷컴] 2번째 숙제 - 두 정수의 연산 (공연 예약 시스템)
[명우니닷컴] 2번째 숙제 - 두 정수의 연산 (공연 예약 시스템)Myeongun Ryu
 
[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
 
[2013 CodeEngn Conference 08] manGoo - Windows 8 Exploit
[2013 CodeEngn Conference 08] manGoo - Windows 8 Exploit[2013 CodeEngn Conference 08] manGoo - Windows 8 Exploit
[2013 CodeEngn Conference 08] manGoo - Windows 8 ExploitGangSeok Lee
 
코딩인카페 C&JAVA 기초과정 C프로그래밍(2)
코딩인카페 C&JAVA 기초과정 C프로그래밍(2)코딩인카페 C&JAVA 기초과정 C프로그래밍(2)
코딩인카페 C&JAVA 기초과정 C프로그래밍(2)유익아카데미
 
Effective c++ item49
Effective c++ item49Effective c++ item49
Effective c++ item49진화 손
 
Effective c++ item27
Effective c++ item27Effective c++ item27
Effective c++ item27진화 손
 
Refelction의 개념과 RTTR 라이브러리
Refelction의 개념과 RTTR 라이브러리Refelction의 개념과 RTTR 라이브러리
Refelction의 개념과 RTTR 라이브러리ssuser7c5a40
 
모어이펙티브 C++ 3,4장 예외, 효율 스터디
모어이펙티브 C++ 3,4장 예외, 효율 스터디모어이펙티브 C++ 3,4장 예외, 효율 스터디
모어이펙티브 C++ 3,4장 예외, 효율 스터디quxn6
 
[C++ korea] effective modern c++ study item 2 understanding auto type deduc...
[C++ korea] effective modern c++ study   item 2 understanding auto type deduc...[C++ korea] effective modern c++ study   item 2 understanding auto type deduc...
[C++ korea] effective modern c++ study item 2 understanding auto type deduc...Seok-joon Yun
 

What's hot (20)

[KOSSA] C++ Programming - 13th Study - exception handling
[KOSSA] C++ Programming - 13th Study - exception handling[KOSSA] C++ Programming - 13th Study - exception handling
[KOSSA] C++ Programming - 13th Study - exception handling
 
[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...
 
Startup JavaScript 3 - 조건문, 반복문, 예외처리
Startup JavaScript 3 - 조건문, 반복문, 예외처리Startup JavaScript 3 - 조건문, 반복문, 예외처리
Startup JavaScript 3 - 조건문, 반복문, 예외처리
 
코딩인카페 C&JAVA 기초과정 C프로그래밍(1)
코딩인카페 C&JAVA 기초과정 C프로그래밍(1)코딩인카페 C&JAVA 기초과정 C프로그래밍(1)
코딩인카페 C&JAVA 기초과정 C프로그래밍(1)
 
C++11
C++11C++11
C++11
 
[C++ korea] effective modern c++ study item 14 declare functions noexcept if ...
[C++ korea] effective modern c++ study item 14 declare functions noexcept if ...[C++ korea] effective modern c++ study item 14 declare functions noexcept if ...
[C++ korea] effective modern c++ study item 14 declare functions noexcept if ...
 
C++11
C++11C++11
C++11
 
[2012 CodeEngn Conference 07] manGoo - Exploit Writing Technique의 발전과 최신 트랜드
[2012 CodeEngn Conference 07] manGoo - Exploit Writing Technique의 발전과 최신 트랜드[2012 CodeEngn Conference 07] manGoo - Exploit Writing Technique의 발전과 최신 트랜드
[2012 CodeEngn Conference 07] manGoo - Exploit Writing Technique의 발전과 최신 트랜드
 
[C++ korea] Effective Modern C++ 신촌 Study Item20,21,23
[C++ korea] Effective Modern C++ 신촌 Study Item20,21,23[C++ korea] Effective Modern C++ 신촌 Study Item20,21,23
[C++ korea] Effective Modern C++ 신촌 Study Item20,21,23
 
코딩인카페 C&JAVA 기초과정 C프로그래밍(3)
코딩인카페 C&JAVA 기초과정 C프로그래밍(3)코딩인카페 C&JAVA 기초과정 C프로그래밍(3)
코딩인카페 C&JAVA 기초과정 C프로그래밍(3)
 
[명우니닷컴] 2번째 숙제 - 두 정수의 연산 (공연 예약 시스템)
[명우니닷컴] 2번째 숙제 - 두 정수의 연산 (공연 예약 시스템)[명우니닷컴] 2번째 숙제 - 두 정수의 연산 (공연 예약 시스템)
[명우니닷컴] 2번째 숙제 - 두 정수의 연산 (공연 예약 시스템)
 
[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...
 
[2013 CodeEngn Conference 08] manGoo - Windows 8 Exploit
[2013 CodeEngn Conference 08] manGoo - Windows 8 Exploit[2013 CodeEngn Conference 08] manGoo - Windows 8 Exploit
[2013 CodeEngn Conference 08] manGoo - Windows 8 Exploit
 
코딩인카페 C&JAVA 기초과정 C프로그래밍(2)
코딩인카페 C&JAVA 기초과정 C프로그래밍(2)코딩인카페 C&JAVA 기초과정 C프로그래밍(2)
코딩인카페 C&JAVA 기초과정 C프로그래밍(2)
 
Changes in c++0x
Changes in c++0xChanges in c++0x
Changes in c++0x
 
Effective c++ item49
Effective c++ item49Effective c++ item49
Effective c++ item49
 
Effective c++ item27
Effective c++ item27Effective c++ item27
Effective c++ item27
 
Refelction의 개념과 RTTR 라이브러리
Refelction의 개념과 RTTR 라이브러리Refelction의 개념과 RTTR 라이브러리
Refelction의 개념과 RTTR 라이브러리
 
모어이펙티브 C++ 3,4장 예외, 효율 스터디
모어이펙티브 C++ 3,4장 예외, 효율 스터디모어이펙티브 C++ 3,4장 예외, 효율 스터디
모어이펙티브 C++ 3,4장 예외, 효율 스터디
 
[C++ korea] effective modern c++ study item 2 understanding auto type deduc...
[C++ korea] effective modern c++ study   item 2 understanding auto type deduc...[C++ korea] effective modern c++ study   item 2 understanding auto type deduc...
[C++ korea] effective modern c++ study item 2 understanding auto type deduc...
 

Similar to Effective modern cpp item14

Modern C++의 타입 추론과 람다, 컨셉
Modern C++의 타입 추론과 람다, 컨셉Modern C++의 타입 추론과 람다, 컨셉
Modern C++의 타입 추론과 람다, 컨셉HyunJoon Park
 
[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++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
 
불어오는 변화의 바람, 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 명신 김
 
카사 공개세미나1회 W.E.L.C.
카사 공개세미나1회  W.E.L.C.카사 공개세미나1회  W.E.L.C.
카사 공개세미나1회 W.E.L.C.Ryan Park
 
김민욱, (달빛조각사) 엘릭서를 이용한 mmorpg 서버 개발, NDC2019
김민욱, (달빛조각사) 엘릭서를 이용한 mmorpg 서버 개발, NDC2019김민욱, (달빛조각사) 엘릭서를 이용한 mmorpg 서버 개발, NDC2019
김민욱, (달빛조각사) 엘릭서를 이용한 mmorpg 서버 개발, NDC2019min woog kim
 
이펙티브 C++ (7~9)
이펙티브 C++ (7~9)이펙티브 C++ (7~9)
이펙티브 C++ (7~9)익성 조
 
MNIST for ML beginners
MNIST for ML beginnersMNIST for ML beginners
MNIST for ML beginners홍배 김
 
Modern C++ 프로그래머를 위한 CPP11/14 핵심
Modern C++ 프로그래머를 위한 CPP11/14 핵심Modern C++ 프로그래머를 위한 CPP11/14 핵심
Modern C++ 프로그래머를 위한 CPP11/14 핵심흥배 최
 
[2B7]시즌2 멀티쓰레드프로그래밍이 왜 이리 힘드나요
[2B7]시즌2 멀티쓰레드프로그래밍이 왜 이리 힘드나요[2B7]시즌2 멀티쓰레드프로그래밍이 왜 이리 힘드나요
[2B7]시즌2 멀티쓰레드프로그래밍이 왜 이리 힘드나요NAVER D2
 
파이썬 스터디 2주차
파이썬 스터디 2주차파이썬 스터디 2주차
파이썬 스터디 2주차Han Sung Kim
 
A tour of C++ : the basics
A tour of C++ : the basicsA tour of C++ : the basics
A tour of C++ : the basicsJaewon Choi
 
1.자료구조와 알고리즘(강의자료)
1.자료구조와 알고리즘(강의자료)1.자료구조와 알고리즘(강의자료)
1.자료구조와 알고리즘(강의자료)fmbvbfhs
 
Effective c++ chapter 1,2 요약
Effective c++ chapter 1,2 요약Effective c++ chapter 1,2 요약
Effective c++ chapter 1,2 요약Nam Hyeonuk
 
Legacy code refactoring video rental system
Legacy code refactoring   video rental systemLegacy code refactoring   video rental system
Legacy code refactoring video rental systemJaehoon Oh
 
모던 C++ 정리
모던 C++ 정리모던 C++ 정리
모던 C++ 정리Hansol Kang
 
NDC11_김성익_슈퍼클래스
NDC11_김성익_슈퍼클래스NDC11_김성익_슈퍼클래스
NDC11_김성익_슈퍼클래스Sungik Kim
 

Similar to Effective modern cpp item14 (20)

Modern C++의 타입 추론과 람다, 컨셉
Modern C++의 타입 추론과 람다, 컨셉Modern C++의 타입 추론과 람다, 컨셉
Modern C++의 타입 추론과 람다, 컨셉
 
[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++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
 
5 swift 기초함수
5 swift 기초함수5 swift 기초함수
5 swift 기초함수
 
불어오는 변화의 바람, 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
 
HI-ARC PS 101
HI-ARC PS 101HI-ARC PS 101
HI-ARC PS 101
 
카사 공개세미나1회 W.E.L.C.
카사 공개세미나1회  W.E.L.C.카사 공개세미나1회  W.E.L.C.
카사 공개세미나1회 W.E.L.C.
 
강의자료 2
강의자료 2강의자료 2
강의자료 2
 
김민욱, (달빛조각사) 엘릭서를 이용한 mmorpg 서버 개발, NDC2019
김민욱, (달빛조각사) 엘릭서를 이용한 mmorpg 서버 개발, NDC2019김민욱, (달빛조각사) 엘릭서를 이용한 mmorpg 서버 개발, NDC2019
김민욱, (달빛조각사) 엘릭서를 이용한 mmorpg 서버 개발, NDC2019
 
이펙티브 C++ (7~9)
이펙티브 C++ (7~9)이펙티브 C++ (7~9)
이펙티브 C++ (7~9)
 
MNIST for ML beginners
MNIST for ML beginnersMNIST for ML beginners
MNIST for ML beginners
 
Modern C++ 프로그래머를 위한 CPP11/14 핵심
Modern C++ 프로그래머를 위한 CPP11/14 핵심Modern C++ 프로그래머를 위한 CPP11/14 핵심
Modern C++ 프로그래머를 위한 CPP11/14 핵심
 
[2B7]시즌2 멀티쓰레드프로그래밍이 왜 이리 힘드나요
[2B7]시즌2 멀티쓰레드프로그래밍이 왜 이리 힘드나요[2B7]시즌2 멀티쓰레드프로그래밍이 왜 이리 힘드나요
[2B7]시즌2 멀티쓰레드프로그래밍이 왜 이리 힘드나요
 
파이썬 스터디 2주차
파이썬 스터디 2주차파이썬 스터디 2주차
파이썬 스터디 2주차
 
A tour of C++ : the basics
A tour of C++ : the basicsA tour of C++ : the basics
A tour of C++ : the basics
 
1.자료구조와 알고리즘(강의자료)
1.자료구조와 알고리즘(강의자료)1.자료구조와 알고리즘(강의자료)
1.자료구조와 알고리즘(강의자료)
 
Effective c++ chapter 1,2 요약
Effective c++ chapter 1,2 요약Effective c++ chapter 1,2 요약
Effective c++ chapter 1,2 요약
 
Legacy code refactoring video rental system
Legacy code refactoring   video rental systemLegacy code refactoring   video rental system
Legacy code refactoring video rental system
 
모던 C++ 정리
모던 C++ 정리모던 C++ 정리
모던 C++ 정리
 
NDC11_김성익_슈퍼클래스
NDC11_김성익_슈퍼클래스NDC11_김성익_슈퍼클래스
NDC11_김성익_슈퍼클래스
 

More from 진화 손

C++20 Remove std::weak_equality and std::strong_equality.pdf
C++20 Remove std::weak_equality and std::strong_equality.pdfC++20 Remove std::weak_equality and std::strong_equality.pdf
C++20 Remove std::weak_equality and std::strong_equality.pdf진화 손
 
C++20 std::execution::unseq.pdf
C++20 std::execution::unseq.pdfC++20 std::execution::unseq.pdf
C++20 std::execution::unseq.pdf진화 손
 
C++ 20 class template argument deduction for alias templates
C++ 20 class template argument deduction for alias templatesC++ 20 class template argument deduction for alias templates
C++ 20 class template argument deduction for alias templates진화 손
 
C++ 20 Make stateful allocator propagation more consistent for operator+(basi...
C++ 20 Make stateful allocator propagation more consistent for operator+(basi...C++ 20 Make stateful allocator propagation more consistent for operator+(basi...
C++ 20 Make stateful allocator propagation more consistent for operator+(basi...진화 손
 
C++ 20 Unevaluated asm-declaration in constexpr functions
C++ 20 Unevaluated asm-declaration in constexpr functionsC++ 20 Unevaluated asm-declaration in constexpr functions
C++ 20 Unevaluated asm-declaration in constexpr functions진화 손
 
C++20 Utility functions to implement uses-allocator construction.pdf
C++20 Utility functions to implement uses-allocator construction.pdfC++20 Utility functions to implement uses-allocator construction.pdf
C++20 Utility functions to implement uses-allocator construction.pdf진화 손
 
C++ 20 std__reference_wrapper for incomplete types
C++ 20 std__reference_wrapper for incomplete typesC++ 20 std__reference_wrapper for incomplete types
C++ 20 std__reference_wrapper for incomplete types진화 손
 
C++ 20 Stronger Unicode requirements
C++ 20 Stronger Unicode requirementsC++ 20 Stronger Unicode requirements
C++ 20 Stronger Unicode requirements진화 손
 
C++20 Concepts library
C++20 Concepts libraryC++20 Concepts library
C++20 Concepts library진화 손
 
C++20 Coroutine
C++20 CoroutineC++20 Coroutine
C++20 Coroutine진화 손
 
C++ 20 Relaxing the range-for loop customization point finding rules
C++ 20 Relaxing the range-for loop customization point finding rulesC++ 20 Relaxing the range-for loop customization point finding rules
C++ 20 Relaxing the range-for loop customization point finding rules진화 손
 
C++ 20 Relaxing the structured bindings customization point finding rules
C++ 20 Relaxing the structured bindings customization point finding rulesC++ 20 Relaxing the structured bindings customization point finding rules
C++ 20 Relaxing the structured bindings customization point finding rules진화 손
 
C++20 explicit(bool)
C++20 explicit(bool)C++20 explicit(bool)
C++20 explicit(bool)진화 손
 
C++20 std::map::contains
C++20 std::map::containsC++20 std::map::contains
C++20 std::map::contains진화 손
 
C++20 Comparing unordered containers
C++20 Comparing unordered containersC++20 Comparing unordered containers
C++20 Comparing unordered containers진화 손
 
C++20 Attributes [[likely]] and [[unlikely]]
C++20 Attributes [[likely]] and [[unlikely]]C++20 Attributes [[likely]] and [[unlikely]]
C++20 Attributes [[likely]] and [[unlikely]]진화 손
 
C++ 20 Lambdas in unevaluated contexts
C++ 20 Lambdas in unevaluated contextsC++ 20 Lambdas in unevaluated contexts
C++ 20 Lambdas in unevaluated contexts진화 손
 
C++20 Library support for operator<=> <compare>
C++20 Library support for operator<=> <compare>C++20 Library support for operator<=> <compare>
C++20 Library support for operator<=> <compare>진화 손
 
C++20 Atomic std::shared_ptr and std::weak_ptr
C++20 Atomic std::shared_ptr and std::weak_ptrC++20 Atomic std::shared_ptr and std::weak_ptr
C++20 Atomic std::shared_ptr and std::weak_ptr진화 손
 
C++20 Default member initializers for bit-fields
C++20 Default member initializers for bit-fieldsC++20 Default member initializers for bit-fields
C++20 Default member initializers for bit-fields진화 손
 

More from 진화 손 (20)

C++20 Remove std::weak_equality and std::strong_equality.pdf
C++20 Remove std::weak_equality and std::strong_equality.pdfC++20 Remove std::weak_equality and std::strong_equality.pdf
C++20 Remove std::weak_equality and std::strong_equality.pdf
 
C++20 std::execution::unseq.pdf
C++20 std::execution::unseq.pdfC++20 std::execution::unseq.pdf
C++20 std::execution::unseq.pdf
 
C++ 20 class template argument deduction for alias templates
C++ 20 class template argument deduction for alias templatesC++ 20 class template argument deduction for alias templates
C++ 20 class template argument deduction for alias templates
 
C++ 20 Make stateful allocator propagation more consistent for operator+(basi...
C++ 20 Make stateful allocator propagation more consistent for operator+(basi...C++ 20 Make stateful allocator propagation more consistent for operator+(basi...
C++ 20 Make stateful allocator propagation more consistent for operator+(basi...
 
C++ 20 Unevaluated asm-declaration in constexpr functions
C++ 20 Unevaluated asm-declaration in constexpr functionsC++ 20 Unevaluated asm-declaration in constexpr functions
C++ 20 Unevaluated asm-declaration in constexpr functions
 
C++20 Utility functions to implement uses-allocator construction.pdf
C++20 Utility functions to implement uses-allocator construction.pdfC++20 Utility functions to implement uses-allocator construction.pdf
C++20 Utility functions to implement uses-allocator construction.pdf
 
C++ 20 std__reference_wrapper for incomplete types
C++ 20 std__reference_wrapper for incomplete typesC++ 20 std__reference_wrapper for incomplete types
C++ 20 std__reference_wrapper for incomplete types
 
C++ 20 Stronger Unicode requirements
C++ 20 Stronger Unicode requirementsC++ 20 Stronger Unicode requirements
C++ 20 Stronger Unicode requirements
 
C++20 Concepts library
C++20 Concepts libraryC++20 Concepts library
C++20 Concepts library
 
C++20 Coroutine
C++20 CoroutineC++20 Coroutine
C++20 Coroutine
 
C++ 20 Relaxing the range-for loop customization point finding rules
C++ 20 Relaxing the range-for loop customization point finding rulesC++ 20 Relaxing the range-for loop customization point finding rules
C++ 20 Relaxing the range-for loop customization point finding rules
 
C++ 20 Relaxing the structured bindings customization point finding rules
C++ 20 Relaxing the structured bindings customization point finding rulesC++ 20 Relaxing the structured bindings customization point finding rules
C++ 20 Relaxing the structured bindings customization point finding rules
 
C++20 explicit(bool)
C++20 explicit(bool)C++20 explicit(bool)
C++20 explicit(bool)
 
C++20 std::map::contains
C++20 std::map::containsC++20 std::map::contains
C++20 std::map::contains
 
C++20 Comparing unordered containers
C++20 Comparing unordered containersC++20 Comparing unordered containers
C++20 Comparing unordered containers
 
C++20 Attributes [[likely]] and [[unlikely]]
C++20 Attributes [[likely]] and [[unlikely]]C++20 Attributes [[likely]] and [[unlikely]]
C++20 Attributes [[likely]] and [[unlikely]]
 
C++ 20 Lambdas in unevaluated contexts
C++ 20 Lambdas in unevaluated contextsC++ 20 Lambdas in unevaluated contexts
C++ 20 Lambdas in unevaluated contexts
 
C++20 Library support for operator<=> <compare>
C++20 Library support for operator<=> <compare>C++20 Library support for operator<=> <compare>
C++20 Library support for operator<=> <compare>
 
C++20 Atomic std::shared_ptr and std::weak_ptr
C++20 Atomic std::shared_ptr and std::weak_ptrC++20 Atomic std::shared_ptr and std::weak_ptr
C++20 Atomic std::shared_ptr and std::weak_ptr
 
C++20 Default member initializers for bit-fields
C++20 Default member initializers for bit-fieldsC++20 Default member initializers for bit-fields
C++20 Default member initializers for bit-fields
 

Effective modern cpp item14

  • 1. Item 14. 예외를 방출하지 않을 함수는 noexcept로 선언하라 Effective Modern C++ 스터디 이데아 게임즈 손진화
  • 2. 예외 명세(exception specification) • 함수를 호출할 때 사용자는 호출하는 함수가 어떤 예외를 발생시키는지 알아야 한다 • C++11에서는 사용하는 함수가 예외를 발생 시키지 않을 수 있다고 보장 할 경우 noexcept 키워드를 사용할 수 있다
  • 3. 예외를 발생시키지 않는 함수 • int f(int x) throw() // C++ 98 • Int f(int x) noexcept // C++ 11
  • 4. 만약 에러가 났을 경우 • throw() // C++ 98 스택 풀기(stack unwind)를 시도하다가 에러 처리 코드를 만나지 못하면 실행이 종료된다 • noexcept - 스택 풀기 수행 여부는 컴파일러마다 다르다 - VS 에서는 에러 처리 코드가 있어도 프로그램이 종료된다
  • 5. 최적화 정도 • Int f(int x) noexcept 최적화 여지가 가장 크다 • int f(int x) throw() 최적화 여지가 더 작다 • int f(int x) 최적화 여지가 더 작다
  • 6. 예제 std::vector<Widget> vw; Widget w; vw.push_back(w); • 이 때 vw의 용량이 넘어 갈 경우 새 벡터를 만 들고 요소들을 복사하고 기존 객체들을 파괴 하여 작업을 완료한다 • 중간에 오류가 나도 안전하다
  • 7. 예제 std::vector<Widget> vw; Widget w; vw.push_back(w); • 이 때 vw의 용량이 넘어 갈 경우 새 벡터를 만 들고 요소들을 이동하여 작업을 완료한다 • 중간에 오류가 나면 망한다 • 오류가 발생하지 않는다면 성능향상을 기대
  • 8. 예제 - 해결 • 예외 발생이 가능한 경우는 move대신 copy 를 한다 • 예외가 발생하지 않는다고 확인되면 move를 사용한다 • 예외 발생 여부는 noexcept 키워드로 지정하면 된다
  • 9. 예제 - 해결 • C++98에서 강한 예외 안전성을 보장하는 함 수들 중에 이런 식으로 동작하는 함수들은 모 두 C++11에서 이렇게 동작하도록 수정되었 다 • std::vector::reserve std::vector::insert td::deque::insert
  • 10. 조건부 noexcept 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))); ... }; // throw() 보다 좋아졌다!
  • 11. noexcept 를 잘 생각하고 사용하자 • noexcept 함수 였다가 후에 바뀌는 경우 • 예외 중립적 함수인 경우 • noexcept를 쓰기 위해 함수 내부에서 예외처리 등을 많이 해두어서 성능상 이득을 못 보는 경우
  • 12. noexcept 를 잘 생각하고 사용하자 • 메모리 해제 함수와 모든 소멸자는 암묵적으 로 noexcept로 선언된다 만약에 바꾸고 싶은 경우 noexcept(false) 사용 • 넓은 계약을 가진 함수들에 대해서만 noexcept 키워드를 사용 void f(const std::string& s) noexcept; // 전제조건 : s.length() <= 32
  • 13. 넓은 계약, 좁은 계약 • 넓은 계약 함수를 호출하기 위한 사전 조건이 존재하지 않는다. • 좁은 계약 넓은 계약을 만족하지 못하는 모든 경우 • 미정의 행동 하지 말라는 행동..
  • 14. noexcept 를 잘 생각하고 사용하자 • 함수 구현과 예외 명세 사이를 컴파일러가 파악해주지 않는다 void setup(); void cleanup(); void init() noexcept { setup(); // … cleanup(); } // ok
  • 15. 결론 • noexcept는 함수의 인터페이스의 일부이다 이는 호출자가 noexcept 여부에 의존할 수 있음을 뜻한다 • noexcept 함수는 비noexcept함수보다 최적화의 여지가 크다
  • 16. 결론 • noexcept는 이동 연산들과 swap, 메모리 해제 함수들, 그리고 소멸자들에 특히나 유용하다 • 대부분의 함수는 noexcept가 아니라 예외에 중립적이다