[C++ Korea] Effective Modern C++ Study item14 16 +신촌

Seok-joon Yun
Seok-joon YunData Engineer, Backend Developer em Zigbang
Effective Modern C++ Study
C++ Korea
[C++ Korea] Effective Modern C++ Study item14 16 +신촌
[C++ Korea] Effective Modern C++ Study item14 16 +신촌
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
[C++ Korea] Effective Modern C++ Study item14 16 +신촌
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
[C++ Korea] Effective Modern C++ Study item14 16 +신촌
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 선언이 없는데…
[C++ Korea] Effective Modern C++ Study item14 16 +신촌
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
[C++ Korea] Effective Modern C++ Study item14 16 +신촌
Effective Modern C++ Study
C++ Korea
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1972.pdf
Effective Modern C++ Study
C++ Korea24
struct S
{
static const int size;
};
const int limit = 2 * S::size; // dynamic initialization
const int S::size = 256;
const int z = numeric_limits::max(); // dynamic initialization
Effective Modern C++ Study
C++ Korea25
Effective Modern C++ Study
C++ Korea
int sz; // non-constexpr variable
constexpr auto arraySize1 = sz; // error! sz's value not
// known at compilation
std::array<int, sz> data1; // error! same problem
constexpr auto arraySize2 = 10; // fine, 10 is a compile-time
// constant
std::array<int, arraySize2> data2; // fine, arraySize2 is constexpr
const auto arraySize = sz; // fine, arraySize is const copy
// of sz
std::array<int, arraySize> data; // error! arraySize's value not
// known at compilation
26
Effective Modern C++ Study
C++ Korea27
Effective Modern C++ Study
C++ Korea
constexpr // pow's a constexpr func
int pow(int base, int exp) noexcept // that never
throws
{
… // impl is below
}
constexpr auto numConds = 5; // # of conditions
std::array<int, pow(3, numConds)> results;
// results has 3^numConds elements
28
Effective Modern C++ Study
C++ Korea
auto base = readFromDB("base"); // get these values
auto exp = readFromDB("exponent"); // at runtime
auto baseToExp = pow(base, exp);
// call pow function at runtime
29
Effective Modern C++ Study
C++ Korea30
constexpr int pow(int base, int exp) noexcept
{
return (exp == 0 ? 1 : base * pow(base, exp - 1));
}
Effective Modern C++ Study
C++ Korea
constexpr int next(int x)
{ return ++x; }
constexpr int twice(int x);
enum { bufsz = twice(256) };
constexpr int fac(int x)
{ return x > 2 ? x * fac(x - 1) : 1; }
extern const int medium;
const int high = square(medium);
31
Effective Modern C++ Study
C++ Korea32
constexpr int pow(int base, int exp) noexcept // C++14
{
auto result = 1;
for (int i = 0; i < exp; ++i) result *= base;
return result;
}
Effective Modern C++ Study
C++ Korea33
class Point {
public:
constexpr Point(double xVal = 0, double yVal = 0) noexcept
: x(xVal), y(yVal) {}
constexpr double xValue() const noexcept{ return x; }
constexpr double yValue() const noexcept{ return y; }
void setX(double newX) noexcept{ x = newX; }
void setY(double newY) noexcept{ y = newY; }
private:
double x, y;
};
Effective Modern C++ Study
C++ Korea34
class Point {
public:
constexpr void setX(double newX) noexcept // C++14
{ x = newX; }
constexpr void setY(double newY) noexcept // C++14
{ y = newY; }
};
- Constexpr은 const임을 암시하기 때문에 의미 상 setter는 부자연스러움, 그러나 C++14에서
는 이를 허용
- Return 값이 void인 것을 허용하지 않았으나 가능해짐
Effective Modern C++ Study
C++ Korea35
// return reflection of p with respect to the origin (C++14)
constexpr Point reflection(const Point& p) noexcept
{
Point result; // create non-const Point
result.setX(-p.xValue()); // set its x and y values
result.setY(-p.yValue());
return result; // return copy of it
}
constexpr Point p1(9.4, 27.7); // as above
constexpr Point p2(28.8, 5.3);
constexpr auto mid = midpoint(p1, p2);
constexpr auto reflectedMid = // reflectedMid's value is
reflection(mid); // (-19.1 -16.5) and known during compilation
Effective Modern C++ Study
C++ Korea36
[C++ Korea] Effective Modern C++ Study item14 16 +신촌
[C++ Korea] Effective Modern C++ Study item14 16 +신촌
Effective Modern C++ Study
C++ Korea39
Effective Modern C++ Study
C++ Korea40
[C++ Korea] Effective Modern C++ Study item14 16 +신촌
Effective Modern C++ Study
C++ Korea42
[C++ Korea] Effective Modern C++ Study item14 16 +신촌
Effective Modern C++ Study
C++ Korea44
Effective Modern C++ Study
C++ Korea45
S :
Thread 1 Thread 2
Newton-lapsen Algorithm Executed double-time.
Effective Modern C++ Study
C++ Korea46
Locking…
Effective Modern C++ Study
C++ Korea47
Effective Modern C++ Study
C++ Korea48
생성자에 lock,
소멸자에 unlock
Effective Modern C++ Study
C++ Korea49
atomic을 이용하면 p_type의 연산 순서를 보증할 수 있다.
Effective Modern C++ Study
C++ Korea50
51
Effective Modern C++ Study
C++ Korea
• const member function도 thread-safe가 필요하다.
• 단일 변수 공유시에는 std::atomic을 이용하자.
1 de 52

Recomendados

[C++ korea] Effective Modern C++ 신촌 Study Item20,21,23 por
[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
1.5K visualizações33 slides
[C++ korea] effective modern c++ study item 17 19 신촌 study por
[C++ korea] effective modern c++ study item 17 19 신촌 study[C++ korea] effective modern c++ study item 17 19 신촌 study
[C++ korea] effective modern c++ study item 17 19 신촌 studySeok-joon Yun
1.2K visualizações61 slides
[C++ Korea] Effective Modern C++ Study, Item 27, 29 - 30 por
[C++ Korea] Effective Modern C++ Study, Item 27, 29 - 30[C++ Korea] Effective Modern C++ Study, Item 27, 29 - 30
[C++ Korea] Effective Modern C++ Study, Item 27, 29 - 30Chris Ohk
2.1K visualizações67 slides
[C++ Korea] Effective Modern C++ Study, Item 11 - 13 por
[C++ Korea] Effective Modern C++ Study, Item 11 - 13[C++ Korea] Effective Modern C++ Study, Item 11 - 13
[C++ Korea] Effective Modern C++ Study, Item 11 - 13Chris Ohk
1.8K visualizações31 slides
[C++ Korea] Effective Modern C++ Sinchon Study Item 37-39 por
[C++ Korea] Effective Modern C++ Sinchon Study Item 37-39[C++ Korea] Effective Modern C++ Sinchon Study Item 37-39
[C++ Korea] Effective Modern C++ Sinchon Study Item 37-39Seok-joon Yun
735 visualizações49 slides
C++20 Key Features Summary por
C++20 Key Features SummaryC++20 Key Features Summary
C++20 Key Features SummaryChris Ohk
9.9K visualizações77 slides

Mais conteúdo relacionado

Mais procurados

Modern C++ 프로그래머를 위한 CPP11/14 핵심 por
Modern C++ 프로그래머를 위한 CPP11/14 핵심Modern C++ 프로그래머를 위한 CPP11/14 핵심
Modern C++ 프로그래머를 위한 CPP11/14 핵심흥배 최
46.7K visualizações100 slides
[C++ Korea 2nd Seminar] Ranges for The Cpp Standard Library por
[C++ Korea 2nd Seminar] Ranges for The Cpp Standard Library[C++ Korea 2nd Seminar] Ranges for The Cpp Standard Library
[C++ Korea 2nd Seminar] Ranges for The Cpp Standard LibraryDongMin Choi
2.4K visualizações82 slides
ライブラリ作成のすゝめ - 事例から見る個人OSS開発の効能 por
ライブラリ作成のすゝめ - 事例から見る個人OSS開発の効能ライブラリ作成のすゝめ - 事例から見る個人OSS開発の効能
ライブラリ作成のすゝめ - 事例から見る個人OSS開発の効能Yoshifumi Kawai
42.8K visualizações44 slides
constexpr関数はコンパイル時処理。これはいい。実行時が霞んで見える。cpuの嬌声が聞こえてきそうだ por
constexpr関数はコンパイル時処理。これはいい。実行時が霞んで見える。cpuの嬌声が聞こえてきそうだconstexpr関数はコンパイル時処理。これはいい。実行時が霞んで見える。cpuの嬌声が聞こえてきそうだ
constexpr関数はコンパイル時処理。これはいい。実行時が霞んで見える。cpuの嬌声が聞こえてきそうだGenya Murakami
52.4K visualizações106 slides
[NDC2016] TERA 서버의 Modern C++ 활용기 por
[NDC2016] TERA 서버의 Modern C++ 활용기[NDC2016] TERA 서버의 Modern C++ 활용기
[NDC2016] TERA 서버의 Modern C++ 활용기Sang Heon Lee
6.8K visualizações64 slides
Effective Modern C++ 勉強会 Item 22 por
Effective Modern C++ 勉強会 Item 22Effective Modern C++ 勉強会 Item 22
Effective Modern C++ 勉強会 Item 22Keisuke Fukuda
2.8K visualizações15 slides

Mais procurados(20)

Modern C++ 프로그래머를 위한 CPP11/14 핵심 por 흥배 최
Modern C++ 프로그래머를 위한 CPP11/14 핵심Modern C++ 프로그래머를 위한 CPP11/14 핵심
Modern C++ 프로그래머를 위한 CPP11/14 핵심
흥배 최46.7K visualizações
[C++ Korea 2nd Seminar] Ranges for The Cpp Standard Library por DongMin Choi
[C++ Korea 2nd Seminar] Ranges for The Cpp Standard Library[C++ Korea 2nd Seminar] Ranges for The Cpp Standard Library
[C++ Korea 2nd Seminar] Ranges for The Cpp Standard Library
DongMin Choi2.4K visualizações
ライブラリ作成のすゝめ - 事例から見る個人OSS開発の効能 por Yoshifumi Kawai
ライブラリ作成のすゝめ - 事例から見る個人OSS開発の効能ライブラリ作成のすゝめ - 事例から見る個人OSS開発の効能
ライブラリ作成のすゝめ - 事例から見る個人OSS開発の効能
Yoshifumi Kawai42.8K visualizações
constexpr関数はコンパイル時処理。これはいい。実行時が霞んで見える。cpuの嬌声が聞こえてきそうだ por Genya Murakami
constexpr関数はコンパイル時処理。これはいい。実行時が霞んで見える。cpuの嬌声が聞こえてきそうだconstexpr関数はコンパイル時処理。これはいい。実行時が霞んで見える。cpuの嬌声が聞こえてきそうだ
constexpr関数はコンパイル時処理。これはいい。実行時が霞んで見える。cpuの嬌声が聞こえてきそうだ
Genya Murakami52.4K visualizações
[NDC2016] TERA 서버의 Modern C++ 활용기 por Sang Heon Lee
[NDC2016] TERA 서버의 Modern C++ 활용기[NDC2016] TERA 서버의 Modern C++ 활용기
[NDC2016] TERA 서버의 Modern C++ 활용기
Sang Heon Lee6.8K visualizações
Effective Modern C++ 勉強会 Item 22 por Keisuke Fukuda
Effective Modern C++ 勉強会 Item 22Effective Modern C++ 勉強会 Item 22
Effective Modern C++ 勉強会 Item 22
Keisuke Fukuda2.8K visualizações
[112]rest에서 graph ql과 relay로 갈아타기 이정우 por NAVER D2
[112]rest에서 graph ql과 relay로 갈아타기 이정우[112]rest에서 graph ql과 relay로 갈아타기 이정우
[112]rest에서 graph ql과 relay로 갈아타기 이정우
NAVER D225.3K visualizações
파이썬 생존 안내서 (자막) por Heungsub Lee
파이썬 생존 안내서 (자막)파이썬 생존 안내서 (자막)
파이썬 생존 안내서 (자막)
Heungsub Lee50K visualizações
[KAIST 채용설명회] 데이터 엔지니어는 무슨 일을 하나요? por Juhong Park
[KAIST 채용설명회] 데이터 엔지니어는 무슨 일을 하나요?[KAIST 채용설명회] 데이터 엔지니어는 무슨 일을 하나요?
[KAIST 채용설명회] 데이터 엔지니어는 무슨 일을 하나요?
Juhong Park2.6K visualizações
クロージャデザインパターン por Moriharu Ohzu
クロージャデザインパターンクロージャデザインパターン
クロージャデザインパターン
Moriharu Ohzu19.6K visualizações
Clean Lambdas & Streams in Java8 por Victor Rentea
Clean Lambdas & Streams in Java8Clean Lambdas & Streams in Java8
Clean Lambdas & Streams in Java8
Victor Rentea45.1K visualizações
Effective c++ item49 por 진화 손
Effective c++ item49Effective c++ item49
Effective c++ item49
진화 손158 visualizações
Boost.勉強会#19東京 Effective Modern C++とC++ Core Guidelines por Shintarou Okada
Boost.勉強会#19東京 Effective Modern C++とC++ Core GuidelinesBoost.勉強会#19東京 Effective Modern C++とC++ Core Guidelines
Boost.勉強会#19東京 Effective Modern C++とC++ Core Guidelines
Shintarou Okada13.1K visualizações
C++17 Key Features Summary - Ver 2 por Chris Ohk
C++17 Key Features Summary - Ver 2C++17 Key Features Summary - Ver 2
C++17 Key Features Summary - Ver 2
Chris Ohk17.6K visualizações
Clean code and Code Smells por Mario Sangiorgio
Clean code and Code SmellsClean code and Code Smells
Clean code and Code Smells
Mario Sangiorgio15.6K visualizações
2016년 비씨카드 신입사원 선배특강 20160719 por Tae Young Lee
2016년 비씨카드 신입사원 선배특강 201607192016년 비씨카드 신입사원 선배특강 20160719
2016년 비씨카드 신입사원 선배특강 20160719
Tae Young Lee636 visualizações
C++20 Coroutine por 진화 손
C++20 CoroutineC++20 Coroutine
C++20 Coroutine
진화 손50 visualizações
オブジェクト指向できていますか? por Moriharu Ohzu
オブジェクト指向できていますか?オブジェクト指向できていますか?
オブジェクト指向できていますか?
Moriharu Ohzu237.5K visualizações
Clean code por Mahmoud Zizo
Clean codeClean code
Clean code
Mahmoud Zizo862 visualizações
第六回渋谷Java Java8のJVM監視を考える por chonaso
第六回渋谷Java Java8のJVM監視を考える第六回渋谷Java Java8のJVM監視を考える
第六回渋谷Java Java8のJVM監視を考える
chonaso15.4K visualizações

Destaque

[Td 2015]디버깅, 어디까지 해봤니 당신이 아마도 몰랐을 디버깅 꿀팁 공개(김희준) por
[Td 2015]디버깅, 어디까지 해봤니 당신이 아마도 몰랐을 디버깅 꿀팁 공개(김희준)[Td 2015]디버깅, 어디까지 해봤니 당신이 아마도 몰랐을 디버깅 꿀팁 공개(김희준)
[Td 2015]디버깅, 어디까지 해봤니 당신이 아마도 몰랐을 디버깅 꿀팁 공개(김희준)Sang Don Kim
3.7K visualizações21 slides
[C++ korea] effective modern c++ study item 3 understand decltype +이동우 por
[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
1.7K visualizações19 slides
[C++ korea] effective modern c++ study item 4 - 6 신촌 por
[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
2.8K visualizações43 slides
[C++ korea] effective modern c++ study item 14 declare functions noexcept if ... por
[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
3K visualizações21 slides
Effective c++ chapter3, 4 요약본 por
Effective c++ chapter3, 4 요약본Effective c++ chapter3, 4 요약본
Effective c++ chapter3, 4 요약본Dong Chan Shin
2.8K visualizações41 slides
덤프 파일을 통한 사후 디버깅 실용 테크닉 NDC2012 por
덤프 파일을 통한 사후 디버깅 실용 테크닉 NDC2012덤프 파일을 통한 사후 디버깅 실용 테크닉 NDC2012
덤프 파일을 통한 사후 디버깅 실용 테크닉 NDC2012Esun Kim
21.2K visualizações137 slides

Destaque(20)

[Td 2015]디버깅, 어디까지 해봤니 당신이 아마도 몰랐을 디버깅 꿀팁 공개(김희준) por Sang Don Kim
[Td 2015]디버깅, 어디까지 해봤니 당신이 아마도 몰랐을 디버깅 꿀팁 공개(김희준)[Td 2015]디버깅, 어디까지 해봤니 당신이 아마도 몰랐을 디버깅 꿀팁 공개(김희준)
[Td 2015]디버깅, 어디까지 해봤니 당신이 아마도 몰랐을 디버깅 꿀팁 공개(김희준)
Sang Don Kim3.7K visualizações
[C++ korea] effective modern c++ study item 3 understand decltype +이동우 por Seok-joon Yun
[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 Yun1.7K visualizações
[C++ korea] effective modern c++ study item 4 - 6 신촌 por 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 신촌
Seok-joon Yun2.8K visualizações
[C++ korea] effective modern c++ study item 14 declare functions noexcept if ... por Seok-joon Yun
[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 Yun3K visualizações
Effective c++ chapter3, 4 요약본 por Dong Chan Shin
Effective c++ chapter3, 4 요약본Effective c++ chapter3, 4 요약본
Effective c++ chapter3, 4 요약본
Dong Chan Shin2.8K visualizações
덤프 파일을 통한 사후 디버깅 실용 테크닉 NDC2012 por Esun Kim
덤프 파일을 통한 사후 디버깅 실용 테크닉 NDC2012덤프 파일을 통한 사후 디버깅 실용 테크닉 NDC2012
덤프 파일을 통한 사후 디버깅 실용 테크닉 NDC2012
Esun Kim21.2K visualizações
[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호) por Sang Don Kim
[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)
[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)
Sang Don Kim2.7K visualizações
[C++ Korea 2nd Seminar] C++17 Key Features Summary por Chris Ohk
[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 Ohk10.5K visualizações
[C++ Korea] Effective Modern C++ MVA item 8 Prefer nullptr to 0 and null +윤석준 por 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 +윤석준
Seok-joon Yun2.4K visualizações
[C++ korea] effective modern c++ study item 7 distinguish between () and {} w... por Seok-joon Yun
[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 Yun2.2K visualizações
[Td 2015]틱틱대도 써야 하는 windows 10 앱 개발, c# tips &amp; tricks(송기수) por Sang Don Kim
[Td 2015]틱틱대도 써야 하는 windows 10 앱 개발, c# tips &amp; tricks(송기수)[Td 2015]틱틱대도 써야 하는 windows 10 앱 개발, c# tips &amp; tricks(송기수)
[Td 2015]틱틱대도 써야 하는 windows 10 앱 개발, c# tips &amp; tricks(송기수)
Sang Don Kim1.3K visualizações
[C++ Korea] Effective Modern C++ MVA item 9 Prefer alias declarations to type... por 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...
Seok-joon Yun3.2K visualizações
[C++ korea] effective modern c++ study item8~10 정은식 por 은식 정
[C++ korea] effective modern c++ study item8~10 정은식[C++ korea] effective modern c++ study item8~10 정은식
[C++ korea] effective modern c++ study item8~10 정은식
은식 정2.6K visualizações
Move semantics por QooJuice
Move semanticsMove semantics
Move semantics
QooJuice1.6K visualizações
5 6 1 por nexthw
5 6 15 6 1
5 6 1
nexthw2.2K visualizações
What’s new in c++11 por Jeongsang Baek
What’s new in c++11What’s new in c++11
What’s new in c++11
Jeongsang Baek1.8K visualizações
[C++ korea] effective modern c++ study item 1정은식 por 은식 정
[C++ korea] effective modern c++ study item 1정은식[C++ korea] effective modern c++ study item 1정은식
[C++ korea] effective modern c++ study item 1정은식
은식 정1.1K visualizações
[Td 2015]windows, linux, mac 신경 안 쓴다. .net 2015와 더더 좋아지는 c# 살짝 훔쳐보기(김명신) por Sang Don Kim
[Td 2015]windows, linux, mac 신경 안 쓴다. .net 2015와 더더 좋아지는 c# 살짝 훔쳐보기(김명신)[Td 2015]windows, linux, mac 신경 안 쓴다. .net 2015와 더더 좋아지는 c# 살짝 훔쳐보기(김명신)
[Td 2015]windows, linux, mac 신경 안 쓴다. .net 2015와 더더 좋아지는 c# 살짝 훔쳐보기(김명신)
Sang Don Kim3.8K visualizações
Effective c++ 1 por 현찬 양
Effective c++ 1Effective c++ 1
Effective c++ 1
현찬 양2.9K visualizações
Effective C++ Chaper 1 por 연우 김
Effective C++ Chaper 1Effective C++ Chaper 1
Effective C++ Chaper 1
연우 김2.8K visualizações

Similar a [C++ Korea] Effective Modern C++ Study item14 16 +신촌

불어오는 변화의 바람, From c++98 to c++11, 14 por
불어오는 변화의 바람, From c++98 to c++11, 14 불어오는 변화의 바람, From c++98 to c++11, 14
불어오는 변화의 바람, From c++98 to c++11, 14 명신 김
160 visualizações54 slides
모던 C++ 정리 por
모던 C++ 정리모던 C++ 정리
모던 C++ 정리Hansol Kang
148 visualizações30 slides
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기 por
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기Chris Ohk
6.8K visualizações79 slides
HI-ARC PS 101 por
HI-ARC PS 101HI-ARC PS 101
HI-ARC PS 101Jae-yeol Lee
140 visualizações48 slides
포트폴리오에서 사용한 모던 C++ por
포트폴리오에서 사용한 모던 C++포트폴리오에서 사용한 모던 C++
포트폴리오에서 사용한 모던 C++KWANGIL KIM
673 visualizações53 slides
[C++ Korea] Effective Modern C++ Study item 24-26 por
[C++ Korea] Effective Modern C++ Study item 24-26[C++ Korea] Effective Modern C++ Study item 24-26
[C++ Korea] Effective Modern C++ Study item 24-26Seok-joon Yun
1.8K visualizações40 slides

Similar a [C++ Korea] Effective Modern C++ Study item14 16 +신촌(20)

불어오는 변화의 바람, From c++98 to c++11, 14 por 명신 김
불어오는 변화의 바람, From c++98 to c++11, 14 불어오는 변화의 바람, From c++98 to c++11, 14
불어오는 변화의 바람, From c++98 to c++11, 14
명신 김160 visualizações
모던 C++ 정리 por Hansol Kang
모던 C++ 정리모던 C++ 정리
모던 C++ 정리
Hansol Kang148 visualizações
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기 por Chris Ohk
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
Chris Ohk6.8K visualizações
HI-ARC PS 101 por Jae-yeol Lee
HI-ARC PS 101HI-ARC PS 101
HI-ARC PS 101
Jae-yeol Lee140 visualizações
포트폴리오에서 사용한 모던 C++ por KWANGIL KIM
포트폴리오에서 사용한 모던 C++포트폴리오에서 사용한 모던 C++
포트폴리오에서 사용한 모던 C++
KWANGIL KIM673 visualizações
[C++ Korea] Effective Modern C++ Study item 24-26 por Seok-joon Yun
[C++ Korea] Effective Modern C++ Study item 24-26[C++ Korea] Effective Modern C++ Study item 24-26
[C++ Korea] Effective Modern C++ Study item 24-26
Seok-joon Yun1.8K visualizações
Modern C++의 타입 추론과 람다, 컨셉 por HyunJoon Park
Modern C++의 타입 추론과 람다, 컨셉Modern C++의 타입 추론과 람다, 컨셉
Modern C++의 타입 추론과 람다, 컨셉
HyunJoon Park205 visualizações
[C++ Korea] Effective Modern C++ mva item 7 distinguish between and {} when c... por Seok-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...
Seok-joon Yun819 visualizações
Effective modern cpp item14 por 진화 손
Effective modern cpp item14Effective modern cpp item14
Effective modern cpp item14
진화 손178 visualizações
Changes in c++0x por Sang Yeon Jeon
Changes in c++0xChanges in c++0x
Changes in c++0x
Sang Yeon Jeon682 visualizações
C++ 프로그래밍 2014-2018년 기말시험 기출문제 por Lee Sang-Ho
C++ 프로그래밍 2014-2018년 기말시험 기출문제C++ 프로그래밍 2014-2018년 기말시험 기출문제
C++ 프로그래밍 2014-2018년 기말시험 기출문제
Lee Sang-Ho2.4K visualizações
Effective Modern C++ MVA item 18 Use std::unique_ptr for exclusive-ownership ... por Seok-joon Yun
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 Yun1.4K visualizações
More effective c++ chapter1 2_dcshin por Dong Chan Shin
More effective c++ chapter1 2_dcshinMore effective c++ chapter1 2_dcshin
More effective c++ chapter1 2_dcshin
Dong Chan Shin1.6K visualizações
Effective c++ chapter1 2_dcshin por Dong Chan Shin
Effective c++ chapter1 2_dcshinEffective c++ chapter1 2_dcshin
Effective c++ chapter1 2_dcshin
Dong Chan Shin463 visualizações
[KOSSA] C++ Programming - 13th Study - exception handling por Seok-joon Yun
[KOSSA] C++ Programming - 13th Study - exception handling[KOSSA] C++ Programming - 13th Study - exception handling
[KOSSA] C++ Programming - 13th Study - exception handling
Seok-joon Yun542 visualizações
Let's Go (golang) por 상욱 송
Let's Go (golang)Let's Go (golang)
Let's Go (golang)
상욱 송13.2K visualizações
Visual Studio를 이용한 어셈블리어 학습 part 1 por YEONG-CHEON YOU
Visual Studio를 이용한 어셈블리어 학습 part 1Visual Studio를 이용한 어셈블리어 학습 part 1
Visual Studio를 이용한 어셈블리어 학습 part 1
YEONG-CHEON YOU732 visualizações
강의자료 2 por Young Wook Kim
강의자료 2강의자료 2
강의자료 2
Young Wook Kim1.1K visualizações
C++ 11 에 대해서 쉽게 알아봅시다 1부 por Gwangwhi Mah
C++ 11 에 대해서 쉽게 알아봅시다 1부C++ 11 에 대해서 쉽게 알아봅시다 1부
C++ 11 에 대해서 쉽게 알아봅시다 1부
Gwangwhi Mah3.9K visualizações
13장 연산자 오버로딩 por 유석 남
13장 연산자 오버로딩13장 연산자 오버로딩
13장 연산자 오버로딩
유석 남2.1K visualizações

Mais de Seok-joon Yun

Retrospective.2020 03 por
Retrospective.2020 03Retrospective.2020 03
Retrospective.2020 03Seok-joon Yun
265 visualizações9 slides
Sprint & Jira por
Sprint & JiraSprint & Jira
Sprint & JiraSeok-joon Yun
959 visualizações39 slides
Eks.introduce.v2 por
Eks.introduce.v2Eks.introduce.v2
Eks.introduce.v2Seok-joon Yun
231 visualizações18 slides
Eks.introduce por
Eks.introduceEks.introduce
Eks.introduceSeok-joon Yun
375 visualizações26 slides
AWS DEV DAY SEOUL 2017 Buliding Serverless Web App - 직방 Image Converter por
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
289 visualizações13 slides
아파트 시세,어쩌다 머신러닝까지 por
아파트 시세,어쩌다 머신러닝까지아파트 시세,어쩌다 머신러닝까지
아파트 시세,어쩌다 머신러닝까지Seok-joon Yun
3.2K visualizações56 slides

Mais de Seok-joon Yun(20)

Retrospective.2020 03 por Seok-joon Yun
Retrospective.2020 03Retrospective.2020 03
Retrospective.2020 03
Seok-joon Yun265 visualizações
Sprint & Jira por Seok-joon Yun
Sprint & JiraSprint & Jira
Sprint & Jira
Seok-joon Yun959 visualizações
Eks.introduce.v2 por Seok-joon Yun
Eks.introduce.v2Eks.introduce.v2
Eks.introduce.v2
Seok-joon Yun231 visualizações
Eks.introduce por Seok-joon Yun
Eks.introduceEks.introduce
Eks.introduce
Seok-joon Yun375 visualizações
AWS DEV DAY SEOUL 2017 Buliding Serverless Web App - 직방 Image Converter por Seok-joon Yun
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 Yun289 visualizações
아파트 시세,어쩌다 머신러닝까지 por Seok-joon Yun
아파트 시세,어쩌다 머신러닝까지아파트 시세,어쩌다 머신러닝까지
아파트 시세,어쩌다 머신러닝까지
Seok-joon Yun3.2K visualizações
Pro typescript.ch07.Exception, Memory, Performance por Seok-joon Yun
Pro typescript.ch07.Exception, Memory, PerformancePro typescript.ch07.Exception, Memory, Performance
Pro typescript.ch07.Exception, Memory, Performance
Seok-joon Yun617 visualizações
Doing math with python.ch07 por Seok-joon Yun
Doing math with python.ch07Doing math with python.ch07
Doing math with python.ch07
Seok-joon Yun451 visualizações
Doing math with python.ch06 por Seok-joon Yun
Doing math with python.ch06Doing math with python.ch06
Doing math with python.ch06
Seok-joon Yun421 visualizações
Doing math with python.ch05 por Seok-joon Yun
Doing math with python.ch05Doing math with python.ch05
Doing math with python.ch05
Seok-joon Yun448 visualizações
Doing math with python.ch04 por Seok-joon Yun
Doing math with python.ch04Doing math with python.ch04
Doing math with python.ch04
Seok-joon Yun444 visualizações
Doing math with python.ch03 por Seok-joon Yun
Doing math with python.ch03Doing math with python.ch03
Doing math with python.ch03
Seok-joon Yun225 visualizações
Doing mathwithpython.ch02 por Seok-joon Yun
Doing mathwithpython.ch02Doing mathwithpython.ch02
Doing mathwithpython.ch02
Seok-joon Yun489 visualizações
Doing math with python.ch01 por Seok-joon Yun
Doing math with python.ch01Doing math with python.ch01
Doing math with python.ch01
Seok-joon Yun414 visualizações
Pro typescript.ch03.Object Orientation in TypeScript por Seok-joon Yun
Pro typescript.ch03.Object Orientation in TypeScriptPro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScript
Seok-joon Yun176 visualizações
C++ Concurrency in Action 9-2 Interrupting threads por Seok-joon Yun
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 Yun1.1K visualizações
Welcome to Modern C++ por Seok-joon Yun
Welcome to Modern C++Welcome to Modern C++
Welcome to Modern C++
Seok-joon Yun509 visualizações
[2015-07-20-윤석준] Oracle 성능 관리 2 por Seok-joon Yun
[2015-07-20-윤석준] Oracle 성능 관리 2[2015-07-20-윤석준] Oracle 성능 관리 2
[2015-07-20-윤석준] Oracle 성능 관리 2
Seok-joon Yun647 visualizações
[2015-07-10-윤석준] Oracle 성능 관리 & v$sysstat por Seok-joon Yun
[2015-07-10-윤석준] Oracle 성능 관리 & v$sysstat[2015-07-10-윤석준] Oracle 성능 관리 & v$sysstat
[2015-07-10-윤석준] Oracle 성능 관리 & v$sysstat
Seok-joon Yun2.8K visualizações
[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4 por Seok-joon Yun
[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4
[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4
Seok-joon Yun1.6K visualizações

[C++ Korea] Effective Modern C++ Study item14 16 +신촌

  • 1. Effective Modern C++ Study C++ Korea
  • 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
  • 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
  • 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 선언이 없는데…
  • 20. Effective Modern C++ Study C++ Korea20 • noexcept는 함수 인터페이스에 속한다. 해당 함수 사용자는 noexcept 여부에 대해서 알아야 한다. • noexcept로 함수를 선언하면 성능상의 이점을 볼 수 있다. • move 연산, swap, 메모리 해제 함수, 소멸자 등에서의 noexcept 여부는 아주 중요하다. • 대부분의 함수들은 noexcept로 선언하지 않고 예외를 처리하는 함수로 선언하는게 더 자연스럽다.
  • 23. Effective Modern C++ Study C++ Korea http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1972.pdf
  • 24. Effective Modern C++ Study C++ Korea24 struct S { static const int size; }; const int limit = 2 * S::size; // dynamic initialization const int S::size = 256; const int z = numeric_limits::max(); // dynamic initialization
  • 25. Effective Modern C++ Study C++ Korea25
  • 26. Effective Modern C++ Study C++ Korea int sz; // non-constexpr variable constexpr auto arraySize1 = sz; // error! sz's value not // known at compilation std::array<int, sz> data1; // error! same problem constexpr auto arraySize2 = 10; // fine, 10 is a compile-time // constant std::array<int, arraySize2> data2; // fine, arraySize2 is constexpr const auto arraySize = sz; // fine, arraySize is const copy // of sz std::array<int, arraySize> data; // error! arraySize's value not // known at compilation 26
  • 27. Effective Modern C++ Study C++ Korea27
  • 28. Effective Modern C++ Study C++ Korea constexpr // pow's a constexpr func int pow(int base, int exp) noexcept // that never throws { … // impl is below } constexpr auto numConds = 5; // # of conditions std::array<int, pow(3, numConds)> results; // results has 3^numConds elements 28
  • 29. Effective Modern C++ Study C++ Korea auto base = readFromDB("base"); // get these values auto exp = readFromDB("exponent"); // at runtime auto baseToExp = pow(base, exp); // call pow function at runtime 29
  • 30. Effective Modern C++ Study C++ Korea30 constexpr int pow(int base, int exp) noexcept { return (exp == 0 ? 1 : base * pow(base, exp - 1)); }
  • 31. Effective Modern C++ Study C++ Korea constexpr int next(int x) { return ++x; } constexpr int twice(int x); enum { bufsz = twice(256) }; constexpr int fac(int x) { return x > 2 ? x * fac(x - 1) : 1; } extern const int medium; const int high = square(medium); 31
  • 32. Effective Modern C++ Study C++ Korea32 constexpr int pow(int base, int exp) noexcept // C++14 { auto result = 1; for (int i = 0; i < exp; ++i) result *= base; return result; }
  • 33. Effective Modern C++ Study C++ Korea33 class Point { public: constexpr Point(double xVal = 0, double yVal = 0) noexcept : x(xVal), y(yVal) {} constexpr double xValue() const noexcept{ return x; } constexpr double yValue() const noexcept{ return y; } void setX(double newX) noexcept{ x = newX; } void setY(double newY) noexcept{ y = newY; } private: double x, y; };
  • 34. Effective Modern C++ Study C++ Korea34 class Point { public: constexpr void setX(double newX) noexcept // C++14 { x = newX; } constexpr void setY(double newY) noexcept // C++14 { y = newY; } }; - Constexpr은 const임을 암시하기 때문에 의미 상 setter는 부자연스러움, 그러나 C++14에서 는 이를 허용 - Return 값이 void인 것을 허용하지 않았으나 가능해짐
  • 35. Effective Modern C++ Study C++ Korea35 // return reflection of p with respect to the origin (C++14) constexpr Point reflection(const Point& p) noexcept { Point result; // create non-const Point result.setX(-p.xValue()); // set its x and y values result.setY(-p.yValue()); return result; // return copy of it } constexpr Point p1(9.4, 27.7); // as above constexpr Point p2(28.8, 5.3); constexpr auto mid = midpoint(p1, p2); constexpr auto reflectedMid = // reflectedMid's value is reflection(mid); // (-19.1 -16.5) and known during compilation
  • 36. Effective Modern C++ Study C++ Korea36
  • 39. Effective Modern C++ Study C++ Korea39
  • 40. Effective Modern C++ Study C++ Korea40
  • 42. Effective Modern C++ Study C++ Korea42
  • 44. Effective Modern C++ Study C++ Korea44
  • 45. Effective Modern C++ Study C++ Korea45 S : Thread 1 Thread 2 Newton-lapsen Algorithm Executed double-time.
  • 46. Effective Modern C++ Study C++ Korea46 Locking…
  • 47. Effective Modern C++ Study C++ Korea47
  • 48. Effective Modern C++ Study C++ Korea48 생성자에 lock, 소멸자에 unlock
  • 49. Effective Modern C++ Study C++ Korea49 atomic을 이용하면 p_type의 연산 순서를 보증할 수 있다.
  • 50. Effective Modern C++ Study C++ Korea50
  • 51. 51
  • 52. Effective Modern C++ Study C++ Korea • const member function도 thread-safe가 필요하다. • 단일 변수 공유시에는 std::atomic을 이용하자.