SlideShare a Scribd company logo
Effective Modern C++ Study
C++ Korea
Speaker : Yun Seok-joon ( icysword77@gmail.com )
[C++ Korea] Effective Modern C++ mva item 7 distinguish between and {} when creating objects +윤석준
1. Object Initializing
2. Uniform Initializer
3. std::initializer_list생성자
4. template 내부에서 object 생성
[C++ Korea] Effective Modern C++ mva item 7 distinguish between and {} when creating objects +윤석준
Effective Modern C++ Study
C++ Korea
Object 초기화할 때 아래와 같이 할 수 있다.
int x(0); // initializer is in parentheses
int y = 0; // initializer follows "="
int z{0}; // initializer is in braces
int z = { 0 }; // initializer is in braces
5
Object 초기화에는 COPY 불가 Object에 대해서는
중괄호 { } , 괄호 ( ) , 대입 = 가 있습니다.
통상적으로 = { } 는 중괄호 { } 와 동일하게 취급됩니다만… 다르게 취급하자는 표준안 N3922가 통과되었습니다.
자세한 내용은 김명신 부장님 Blog 에 관련 글이 있습니다.
김명신의 즐거운 하루 - C++11 auto 와 {}-init-list의 모호함 : http://egloos.zum.com/himskim/v/4049007
Effective Modern C++ Study
C++ Korea
non-static value에 대한 default 초기값을 설정하는데
중괄호 { } , 대입 = 는 OK
괄호 ( ) 는 Error
6
class Widget
{
private:
int x{0}; // fine. x's default value is 0
int y = 0; // also fine
int z(0); // error!
};
Effective Modern C++ Study
C++ Korea7
std::atomic<int> ai1{0}; // fine
std::atomic<int> ai2(0); // fine
std::atomic<int> ai3 = 0; // error!
COPY 불가 Object에 대해서는
중괄호 { } , 괄호 ( ) 는 OK
대입 = 은 Error
Effective Modern C++ Study
C++ Korea8
중괄호 { }
Uniform Initializer
[C++ Korea] Effective Modern C++ mva item 7 distinguish between and {} when creating objects +윤석준
Effective Modern C++ Study
C++ Korea10
모든 상황에 다 사용이 가능하다.
+ 기존에 불가능 했던 것을 쉽게 사용할 수 있게 해 주었다.
std::vector<int> v{ 1, 3, 5 }; // v's initial content is 1, 3, 5
Effective Modern C++ Study
C++ Korea11
 Narrowing conversion 방지
class Widget {
public:
Widget(std::initializer_list<bool> il);
...
};
Widget w{10, 5.0}; // error! invalid narrowing conversion from 'double' to 'bool'
Effective Modern C++ Study
C++ Korea12
• Most vexing parse 방지
class Widget {
public:
Widget();
Widget(std::initializer_list<int> il);
...
};
Widget w1; // calls default ctor
Widget w2{}; // also calls default ctor
Widget w3(); // most vexing parse! declares a function!
http://devluna.blogspot.kr/2015/01/item-6-c-most-vexing-parse.html
[C++ Korea] Effective Modern C++ mva item 7 distinguish between and {} when creating objects +윤석준
Effective Modern C++ Study
C++ Korea
std::initializer_list
14
- 생성자의 인자로 std::initializer_list 를 받는 것
- 없다면 개체 초기화에 괄호 ( ) 와 중괄호 { }가 같은 의미
- 있다면 중괄호 { } 를 이용한 초기화는 std::initializer_list 를 호출
class Widget
{
public:
Widget(std::initializer_list<long double> il);
...
};
Effective Modern C++ Study
C++ Korea
std::initializer_list
15
중괄호 { }를 이용한 초기화는 무조건 std::initializer_list 생성자를 호출한다.
(더 적합한 생성자가 있음에도 불구하고…)
class Widget
{
public:
Widget(int i, bool b);
Widget(int i, double d);
Widget(std::initializer_list<long double> il);
...
};
Widget w2{ 10, true }; // 10 and true convert to long double
Widget w4{ 10, 5.0 }; // 10 and 5.0 convert to long double
Effective Modern C++ Study
C++ Korea
std::initializer_list
16
단, Casting이 불가능한 경우는 포기하더라.
class Widget {
public:
Widget(int i, bool b);
Widget(int i, double d);
Widget(std::initializer_list<std::string> il); // std::string로 바꿈
...
};
Widget w1(10, true); // use parens, still calls first ctor
Widget w2{10, true}; // use braces, now calls first ctor
Widget w3(10, 5.0); // use parens, still calls second ctor
Widget w4{10, 5.0}; // use braces, now calls second ctor
[C++ Korea] Effective Modern C++ mva item 7 distinguish between and {} when creating objects +윤석준
Effective Modern C++ Study
C++ Korea18
괄호 ( ) 초기화 , 중괄호 { } 초기화가 다르다면 ?
std::vector<int> v2(10, 20); // use non-std::initializer_list ctor
// create 10-element, all elements have value of 20
std::vector<int> v2{10, 20}; // use std::initializer_list ctor
// create 2-element, element values are 10 and 20
Effective Modern C++ Study
C++ Korea19
template 내부에서 객체를 생성하는 경우 ???
template<typename T, // type of object to create
typename... Ts> // type of arguments to use
void doSomeWork(Ts&&... params)
{
create local T object from params...
}
T localObject(std::forware<Ts>(params)...);
T localObject{std::forward<Ts>(params)...};
std::vector<int> v;
...
doSomeWork<std::vector<int>>(10, 20);
Effective Modern C++ Study
C++ Korea20
• 중괄호 { } 초기화는 모든 경우에 사용 가능한 초기화이며,
narrowing conversion과 most vexing parse를 막아줍니다.
• 생성자들 중에서 중괄호 { } 초기화는 더 완벽해 보이는 다른 생성자가 있음에도 불구하고
불가능한 경우를 제외하고는 std::initializer_list를 호출하고자 합니다.
• 괄호 ( ) 초기화와 중괄호 { } 초기화 중 뭐를 선택하느냐에 따라 다른 결과가 생성되는 예로는
std::vector<numeric type>을 2개의 인자로 생성하는 경우가 있습니다.
• template내에서 객체 생성시 괄호 ( ) 와 중괄호 { } 중 뭐를 선택하냐는 것은 심사숙고 해야 합니다.
http://devluna.blogspot.kr/2015/01/item-7-object.html
icysword77@gmail.com

More Related Content

PDF
[C++ Korea] Effective Modern C++ MVA item 8 Prefer nullptr to 0 and null +윤석준
PDF
[C++ Korea] Effective Modern C++ MVA item 9 Prefer alias declarations to type...
PDF
[C++ korea] effective modern c++ study item 7 distinguish between () and {} w...
PDF
[C++ korea] effective modern c++ study item 14 declare functions noexcept if ...
PPTX
[C++ korea] effective modern c++ study item8~10 정은식
PDF
[C++ korea] Effective Modern C++ 신촌 Study Item20,21,23
PDF
[C++ korea] Effective Modern C++ study item 19 use shared ptr for shared owne...
PDF
[C++ Korea] Effective Modern C++ Study item14 16 +신촌
[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++ study item 7 distinguish between () and {} w...
[C++ korea] effective modern c++ study item 14 declare functions noexcept if ...
[C++ korea] effective modern c++ study item8~10 정은식
[C++ korea] Effective Modern C++ 신촌 Study Item20,21,23
[C++ korea] Effective Modern C++ study item 19 use shared ptr for shared owne...
[C++ Korea] Effective Modern C++ Study item14 16 +신촌

What's hot (20)

PDF
[C++ korea] effective modern c++ study item 17 19 신촌 study
PDF
[C++ Korea] Effective Modern C++ Study item 24-26
PDF
Effective Modern C++ MVA item 18 Use std::unique_ptr for exclusive-ownership ...
PDF
[C++ Korea] Effective Modern C++ Study, Item 1 - 3
PPTX
C++ 타입 추론
PDF
[C++ korea] effective modern c++ study item 2 understanding auto type deduc...
PDF
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
PDF
C++17 Key Features Summary - Ver 2
PPTX
Visual studio 2010
PDF
C++20 Key Features Summary
PDF
2013 C++ Study For Students #1
PDF
[C++ Korea 2nd Seminar] C++17 Key Features Summary
PPTX
Changes in c++0x
PDF
Modern C++ 프로그래머를 위한 CPP11/14 핵심
PPTX
불어오는 변화의 바람, From c++98 to c++11, 14
PPTX
C++11
PDF
C++ Concurrency in Action 9-2 Interrupting threads
PDF
[C++ Korea 3rd Seminar] 새 C++은 새 Visual Studio에, 좌충우돌 마이그레이션 이야기
PPTX
[C++ korea] effective modern c++ study item 1정은식
PDF
[C++ korea] effective modern c++ study item 1 understand template type dedu...
[C++ korea] effective modern c++ study item 17 19 신촌 study
[C++ Korea] Effective Modern C++ Study item 24-26
Effective Modern C++ MVA item 18 Use std::unique_ptr for exclusive-ownership ...
[C++ Korea] Effective Modern C++ Study, Item 1 - 3
C++ 타입 추론
[C++ korea] effective modern c++ study item 2 understanding auto type deduc...
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
C++17 Key Features Summary - Ver 2
Visual studio 2010
C++20 Key Features Summary
2013 C++ Study For Students #1
[C++ Korea 2nd Seminar] C++17 Key Features Summary
Changes in c++0x
Modern C++ 프로그래머를 위한 CPP11/14 핵심
불어오는 변화의 바람, From c++98 to c++11, 14
C++11
C++ Concurrency in Action 9-2 Interrupting threads
[C++ Korea 3rd Seminar] 새 C++은 새 Visual Studio에, 좌충우돌 마이그레이션 이야기
[C++ korea] effective modern c++ study item 1정은식
[C++ korea] effective modern c++ study item 1 understand template type dedu...
Ad

Similar to [C++ Korea] Effective Modern C++ mva item 7 distinguish between and {} when creating objects +윤석준 (20)

PDF
코드 생성을 사용해 개발 속도 높이기 NDC2011
PPTX
NDC 2011, 네트워크 비동기 통신, 합의점의 길목에서
PPTX
Effective c++(chapter 5,6)
PDF
Effective C++ Chapter 1 Summary
PPT
Boost라이브러리의내부구조 20151111 서진택
PPTX
포트폴리오에서 사용한 모던 C++
PDF
코틀린 멀티플랫폼, 미지와의 조우
PDF
More effective c++ chapter1 2_dcshin
PDF
여러 생성자
PDF
[143] Modern C++ 무조건 써야 해?
PDF
[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)
PDF
Effective c++ chapter1 2_dcshin
PPTX
C++ 11 에 대해서 쉽게 알아봅시다 1부
PDF
이더리움 기반 DApp 개발과 스마트 계약 실습 (ERC20,ERC721,ERC1155,ERC1400)
PDF
C++에서 Objective-C까지
PDF
Secrets of the JavaScript Ninja - Chapter 12. DOM modification
PPTX
Effective c++ Chapter1,2
PPT
카사 공개세미나1회 W.E.L.C.
PDF
08장 객체와 클래스 (기본)
PDF
Android ndk jni 설치및 연동
코드 생성을 사용해 개발 속도 높이기 NDC2011
NDC 2011, 네트워크 비동기 통신, 합의점의 길목에서
Effective c++(chapter 5,6)
Effective C++ Chapter 1 Summary
Boost라이브러리의내부구조 20151111 서진택
포트폴리오에서 사용한 모던 C++
코틀린 멀티플랫폼, 미지와의 조우
More effective c++ chapter1 2_dcshin
여러 생성자
[143] Modern C++ 무조건 써야 해?
[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)
Effective c++ chapter1 2_dcshin
C++ 11 에 대해서 쉽게 알아봅시다 1부
이더리움 기반 DApp 개발과 스마트 계약 실습 (ERC20,ERC721,ERC1155,ERC1400)
C++에서 Objective-C까지
Secrets of the JavaScript Ninja - Chapter 12. DOM modification
Effective c++ Chapter1,2
카사 공개세미나1회 W.E.L.C.
08장 객체와 클래스 (기본)
Android ndk jni 설치및 연동
Ad

More from Seok-joon Yun (20)

PDF
Retrospective.2020 03
PDF
Sprint & Jira
PPTX
Eks.introduce.v2
PDF
Eks.introduce
PDF
AWS DEV DAY SEOUL 2017 Buliding Serverless Web App - 직방 Image Converter
PDF
아파트 시세,어쩌다 머신러닝까지
PPTX
Pro typescript.ch07.Exception, Memory, Performance
PPTX
Doing math with python.ch07
PPTX
Doing math with python.ch06
PPTX
Doing math with python.ch05
PPTX
Doing math with python.ch04
PPTX
Doing math with python.ch03
PPTX
Doing mathwithpython.ch02
PPTX
Doing math with python.ch01
PPTX
Pro typescript.ch03.Object Orientation in TypeScript
PDF
Welcome to Modern C++
PDF
[2015-07-20-윤석준] Oracle 성능 관리 2
PDF
[2015-07-10-윤석준] Oracle 성능 관리 & v$sysstat
PDF
[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4
PDF
오렌지6.0 교육자료
Retrospective.2020 03
Sprint & Jira
Eks.introduce.v2
Eks.introduce
AWS DEV DAY SEOUL 2017 Buliding Serverless Web App - 직방 Image Converter
아파트 시세,어쩌다 머신러닝까지
Pro typescript.ch07.Exception, Memory, Performance
Doing math with python.ch07
Doing math with python.ch06
Doing math with python.ch05
Doing math with python.ch04
Doing math with python.ch03
Doing mathwithpython.ch02
Doing math with python.ch01
Pro typescript.ch03.Object Orientation in TypeScript
Welcome to Modern C++
[2015-07-20-윤석준] Oracle 성능 관리 2
[2015-07-10-윤석준] Oracle 성능 관리 & v$sysstat
[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4
오렌지6.0 교육자료

[C++ Korea] Effective Modern C++ mva item 7 distinguish between and {} when creating objects +윤석준

  • 1. Effective Modern C++ Study C++ Korea Speaker : Yun Seok-joon ( icysword77@gmail.com )
  • 3. 1. Object Initializing 2. Uniform Initializer 3. std::initializer_list생성자 4. template 내부에서 object 생성
  • 5. Effective Modern C++ Study C++ Korea Object 초기화할 때 아래와 같이 할 수 있다. int x(0); // initializer is in parentheses int y = 0; // initializer follows "=" int z{0}; // initializer is in braces int z = { 0 }; // initializer is in braces 5 Object 초기화에는 COPY 불가 Object에 대해서는 중괄호 { } , 괄호 ( ) , 대입 = 가 있습니다. 통상적으로 = { } 는 중괄호 { } 와 동일하게 취급됩니다만… 다르게 취급하자는 표준안 N3922가 통과되었습니다. 자세한 내용은 김명신 부장님 Blog 에 관련 글이 있습니다. 김명신의 즐거운 하루 - C++11 auto 와 {}-init-list의 모호함 : http://egloos.zum.com/himskim/v/4049007
  • 6. Effective Modern C++ Study C++ Korea non-static value에 대한 default 초기값을 설정하는데 중괄호 { } , 대입 = 는 OK 괄호 ( ) 는 Error 6 class Widget { private: int x{0}; // fine. x's default value is 0 int y = 0; // also fine int z(0); // error! };
  • 7. Effective Modern C++ Study C++ Korea7 std::atomic<int> ai1{0}; // fine std::atomic<int> ai2(0); // fine std::atomic<int> ai3 = 0; // error! COPY 불가 Object에 대해서는 중괄호 { } , 괄호 ( ) 는 OK 대입 = 은 Error
  • 8. Effective Modern C++ Study C++ Korea8 중괄호 { } Uniform Initializer
  • 10. Effective Modern C++ Study C++ Korea10 모든 상황에 다 사용이 가능하다. + 기존에 불가능 했던 것을 쉽게 사용할 수 있게 해 주었다. std::vector<int> v{ 1, 3, 5 }; // v's initial content is 1, 3, 5
  • 11. Effective Modern C++ Study C++ Korea11  Narrowing conversion 방지 class Widget { public: Widget(std::initializer_list<bool> il); ... }; Widget w{10, 5.0}; // error! invalid narrowing conversion from 'double' to 'bool'
  • 12. Effective Modern C++ Study C++ Korea12 • Most vexing parse 방지 class Widget { public: Widget(); Widget(std::initializer_list<int> il); ... }; Widget w1; // calls default ctor Widget w2{}; // also calls default ctor Widget w3(); // most vexing parse! declares a function! http://devluna.blogspot.kr/2015/01/item-6-c-most-vexing-parse.html
  • 14. Effective Modern C++ Study C++ Korea std::initializer_list 14 - 생성자의 인자로 std::initializer_list 를 받는 것 - 없다면 개체 초기화에 괄호 ( ) 와 중괄호 { }가 같은 의미 - 있다면 중괄호 { } 를 이용한 초기화는 std::initializer_list 를 호출 class Widget { public: Widget(std::initializer_list<long double> il); ... };
  • 15. Effective Modern C++ Study C++ Korea std::initializer_list 15 중괄호 { }를 이용한 초기화는 무조건 std::initializer_list 생성자를 호출한다. (더 적합한 생성자가 있음에도 불구하고…) class Widget { public: Widget(int i, bool b); Widget(int i, double d); Widget(std::initializer_list<long double> il); ... }; Widget w2{ 10, true }; // 10 and true convert to long double Widget w4{ 10, 5.0 }; // 10 and 5.0 convert to long double
  • 16. Effective Modern C++ Study C++ Korea std::initializer_list 16 단, Casting이 불가능한 경우는 포기하더라. class Widget { public: Widget(int i, bool b); Widget(int i, double d); Widget(std::initializer_list<std::string> il); // std::string로 바꿈 ... }; Widget w1(10, true); // use parens, still calls first ctor Widget w2{10, true}; // use braces, now calls first ctor Widget w3(10, 5.0); // use parens, still calls second ctor Widget w4{10, 5.0}; // use braces, now calls second ctor
  • 18. Effective Modern C++ Study C++ Korea18 괄호 ( ) 초기화 , 중괄호 { } 초기화가 다르다면 ? std::vector<int> v2(10, 20); // use non-std::initializer_list ctor // create 10-element, all elements have value of 20 std::vector<int> v2{10, 20}; // use std::initializer_list ctor // create 2-element, element values are 10 and 20
  • 19. Effective Modern C++ Study C++ Korea19 template 내부에서 객체를 생성하는 경우 ??? template<typename T, // type of object to create typename... Ts> // type of arguments to use void doSomeWork(Ts&&... params) { create local T object from params... } T localObject(std::forware<Ts>(params)...); T localObject{std::forward<Ts>(params)...}; std::vector<int> v; ... doSomeWork<std::vector<int>>(10, 20);
  • 20. Effective Modern C++ Study C++ Korea20 • 중괄호 { } 초기화는 모든 경우에 사용 가능한 초기화이며, narrowing conversion과 most vexing parse를 막아줍니다. • 생성자들 중에서 중괄호 { } 초기화는 더 완벽해 보이는 다른 생성자가 있음에도 불구하고 불가능한 경우를 제외하고는 std::initializer_list를 호출하고자 합니다. • 괄호 ( ) 초기화와 중괄호 { } 초기화 중 뭐를 선택하느냐에 따라 다른 결과가 생성되는 예로는 std::vector<numeric type>을 2개의 인자로 생성하는 경우가 있습니다. • template내에서 객체 생성시 괄호 ( ) 와 중괄호 { } 중 뭐를 선택하냐는 것은 심사숙고 해야 합니다. http://devluna.blogspot.kr/2015/01/item-7-object.html icysword77@gmail.com