SlideShare a Scribd company logo
Effective Modern C++ Study
C++ Korea
발표자 : 윤석준
[C++ korea] effective modern c++ study item 7 distinguish between () and {} when creating objects +윤석준
[C++ korea] effective modern c++ study 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
4
http://egloos.zum.com/himskim/v/4049007
Effective Modern C++ Study
C++ Korea
C++ 초보자들에게 = 는 공간을 할당하는 명령어로 오해되기 쉽지만, 사실은 그렇지 않다.
Widget w1; // call default constructor
Widget w2 = w1; // not an assignment; calls copy ctor
w1 = w2; // an assignment; calls copy operator =
5
Effective Modern C++ Study
C++ Korea
non-static value에 대한
default 초기값을 설정하는데
( )는 안된다.
6
class Widget
{
private:
int x{0}; // fine. x's default value is 0
int y = 0; // also fine
int z(0); // error!
};
std::atomic<int> ai1{0}; // fine
std::atomic<int> ai2(0); // fine
std::atomic<int> ai3 = 0; // error!
copy가 안되는 object에 대해서는
()는 되는데, =는 안된다.
둘 다 가능한건 { } 뿐이다.
Effective Modern C++ Study
C++ Korea7
- 모든 상황에 다 사용이 가능하다.
+ 기존에 불가능 했던 것을 쉽게 사용할 수 있게 해 주었다.
std::vector<int> v{ 1, 3, 5 }; // v's initial content is 1, 3, 5
[C++ korea] effective modern c++ study item 7 distinguish between () and {} when creating objects +윤석준
Effective Modern C++ Study
C++ Korea9
{ }를 이용한 생성자는 가능한 무조건 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++ Korea10
단, 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
Effective Modern C++ Study
C++ Korea11
1. 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
2. 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
Effective Modern C++ Study
C++ Korea13
( ) 초기화 와 { } 초기화가 다르게 동작한다면 ???
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++ Korea14
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++ Korea15
• { } 초기화는 가장 널리 사용가능한 초기화이며, 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

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

What's hot (20)

PDF
Effective Modern C++ MVA item 18 Use std::unique_ptr for exclusive-ownership ...
PDF
[C++ Korea] Effective Modern C++ Study item 24-26
PDF
[C++ korea] effective modern c++ study item 17 19 신촌 study
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
PPTX
Changes in c++0x
PDF
C++20 Key Features Summary
PDF
2013 C++ Study For Students #1
PDF
[C++ Korea 2nd Seminar] C++17 Key Features Summary
PDF
Modern C++ 프로그래머를 위한 CPP11/14 핵심
PPTX
C++11
PDF
C++ Concurrency in Action 9-2 Interrupting threads
PPTX
C++11
PPTX
[C++ korea] effective modern c++ study item 1정은식
PPTX
[Pl in c++] 9. 다형성
PDF
[C++ korea] effective modern c++ study item 1 understand template type dedu...
Effective Modern C++ MVA item 18 Use std::unique_ptr for exclusive-ownership ...
[C++ Korea] Effective Modern C++ Study item 24-26
[C++ korea] effective modern c++ study item 17 19 신촌 study
[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
Changes in c++0x
C++20 Key Features Summary
2013 C++ Study For Students #1
[C++ Korea 2nd Seminar] C++17 Key Features Summary
Modern C++ 프로그래머를 위한 CPP11/14 핵심
C++11
C++ Concurrency in Action 9-2 Interrupting threads
C++11
[C++ korea] effective modern c++ study item 1정은식
[Pl in c++] 9. 다형성
[C++ korea] effective modern c++ study item 1 understand template type dedu...
Ad

Similar to [C++ korea] effective modern c++ study item 7 distinguish between () and {} when creating objects +윤석준 (20)

PPTX
Effective c++(chapter 5,6)
PPTX
포트폴리오에서 사용한 모던 C++
PDF
여러 생성자
PDF
More effective c++ chapter1 2_dcshin
PDF
[143] Modern C++ 무조건 써야 해?
PPTX
불어오는 변화의 바람, From c++98 to c++11, 14
PPT
Boost라이브러리의내부구조 20151111 서진택
PDF
100828 [visual studio camp #1] C++0x와 Windows7
PPT
카사 공개세미나1회 W.E.L.C.
PDF
C++ Advanced 강의 2주차
PPTX
NDC 2011, 네트워크 비동기 통신, 합의점의 길목에서
PDF
Android ndk jni 설치및 연동
PDF
[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)
PPTX
java_2장.pptx
PDF
C++에서 Objective-C까지
PDF
초보를 위한 C++11
PDF
W14 chap13
PPTX
C++ 11 에 대해서 쉽게 알아봅시다 1부
PPTX
[C++ Korea 2nd Seminar] Ranges for The Cpp Standard Library
PDF
Effective c++ chapter1 2_dcshin
Effective c++(chapter 5,6)
포트폴리오에서 사용한 모던 C++
여러 생성자
More effective c++ chapter1 2_dcshin
[143] Modern C++ 무조건 써야 해?
불어오는 변화의 바람, From c++98 to c++11, 14
Boost라이브러리의내부구조 20151111 서진택
100828 [visual studio camp #1] C++0x와 Windows7
카사 공개세미나1회 W.E.L.C.
C++ Advanced 강의 2주차
NDC 2011, 네트워크 비동기 통신, 합의점의 길목에서
Android ndk jni 설치및 연동
[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)
java_2장.pptx
C++에서 Objective-C까지
초보를 위한 C++11
W14 chap13
C++ 11 에 대해서 쉽게 알아봅시다 1부
[C++ Korea 2nd Seminar] Ranges for The Cpp Standard Library
Effective c++ chapter1 2_dcshin
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++ study item 7 distinguish between () and {} when creating objects +윤석준

  • 1. Effective Modern C++ Study C++ Korea 발표자 : 윤석준
  • 4. 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 4 http://egloos.zum.com/himskim/v/4049007
  • 5. Effective Modern C++ Study C++ Korea C++ 초보자들에게 = 는 공간을 할당하는 명령어로 오해되기 쉽지만, 사실은 그렇지 않다. Widget w1; // call default constructor Widget w2 = w1; // not an assignment; calls copy ctor w1 = w2; // an assignment; calls copy operator = 5
  • 6. Effective Modern C++ Study C++ Korea non-static value에 대한 default 초기값을 설정하는데 ( )는 안된다. 6 class Widget { private: int x{0}; // fine. x's default value is 0 int y = 0; // also fine int z(0); // error! }; std::atomic<int> ai1{0}; // fine std::atomic<int> ai2(0); // fine std::atomic<int> ai3 = 0; // error! copy가 안되는 object에 대해서는 ()는 되는데, =는 안된다. 둘 다 가능한건 { } 뿐이다.
  • 7. Effective Modern C++ Study C++ Korea7 - 모든 상황에 다 사용이 가능하다. + 기존에 불가능 했던 것을 쉽게 사용할 수 있게 해 주었다. std::vector<int> v{ 1, 3, 5 }; // v's initial content is 1, 3, 5
  • 9. Effective Modern C++ Study C++ Korea9 { }를 이용한 생성자는 가능한 무조건 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
  • 10. Effective Modern C++ Study C++ Korea10 단, 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
  • 11. Effective Modern C++ Study C++ Korea11 1. 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 2. 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
  • 13. Effective Modern C++ Study C++ Korea13 ( ) 초기화 와 { } 초기화가 다르게 동작한다면 ??? 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
  • 14. Effective Modern C++ Study C++ Korea14 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);
  • 15. Effective Modern C++ Study C++ Korea15 • { } 초기화는 가장 널리 사용가능한 초기화이며, narrowing conversion과 most vexing parse를 막아준다. • 생성자들 중에서 {} 초기화는 더 완벽해보이는 다른 생성자가 있음에도 불구하고 불가능한 경우를 제외하고는 std::initializer_list를 호출하고자 한다. • ( ) 와 { } 중 뭐를 선택하느냐에 따라 다른 결과가 생성되는 예로는 std::vector<numeric type>을 2개의 인자로 생성하는 경우가 있다. • template내에서 객체 생성시 ( )와 { } 중 뭐를 선택하냐는 것은 심사숙고 해야 한다.