SlideShare a Scribd company logo
1 of 40
Download to read offline
Effective Modern C++ Study
C++ Korea
Effective Modern C++ Study
C++ Korea3
불필요한 복사를 줄이기
위해 레퍼런스로 받음.
R-Value는 받을 수 없음.
Effective Modern C++ Study
C++ Korea4
Effective Modern C++ Study
C++ Korea
w의 타입은 Widget&
w의 타입은 Widget&&
Effective Modern C++ Study
C++ Korea6
• R-Value Reference • Universal Reference
std::vector<T>의 T는 param과 독립적.
Effective Modern C++ Study
C++ Korea7
• Universal Reference 아님.
• R-Value만 받을 수 있다.
• 타입 추론이 발생
하지 않는다.
Effective Modern C++ Study
C++ Korea8
Effective Modern C++ Study
C++ Korea9
Effective Modern C++ Study
C++ Korea11
Effective Modern C++ Study
C++ Korea12
Effective Modern C++ Study
C++ Korea13
Effective Modern C++ Study
C++ Korea14
Effective Modern C++ Study
C++ Korea15
Effective Modern C++ Study
C++ Korea16
//지역변수 n이 w.setName으로 이동
Effective Modern C++ Study
C++ Korea17
Effective Modern C++ Study
C++ Korea18
Effective Modern C++ Study
C++ Korea19
Effective Modern C++ Study
C++ Korea20
Effective Modern C++ Study
C++ Korea21
Effective Modern C++ Study
C++ Korea22
Effective Modern C++ Study
C++ Korea23
Effective Modern C++ Study
C++ Korea24
Effective Modern C++ Study
C++ Korea25
Effective Modern C++ Study
C++ Korea26
Effective Modern C++ Study
C++ Korea27
RVO
Effective Modern C++ Study
C++ Korea28
A : 조건 2에 부합하지 않음
Effective Modern C++ Study
C++ Korea29
Effective Modern C++ Study
C++ Korea30
Effective Modern C++ Study
C++ Korea31
Effective Modern C++ Study
C++ Korea33
std::multiset<std::string> History; // Global Log History
void Log(const std::string& item)
{
History.emplace(item);
}
std::string name("Luna");
Log(name);
Log(std::string("Star"));
Log("Seokjoon");
// Parameter로 name이라는 변수가 사용됨.
// L-Value가 emplace로 COPY
// Parameter로 R-Value가 전달되었지만,
// item이 L-Value라서 결국 emplace로 COPY
// Parameter로 R-Value가 전달되었지만,
// 임시로 std::string 개체가 만들어져서 결국 emplace로 COPY
Universal Reference + std::forward 면 efficient하게 할 수 있다.
Effective Modern C++ Study
C++ Korea34
std::multiset<std::string> History; // Global Log History
template<typename T>
void Log(T&& item)
{
History.emplace(std::forward<T>(item));
}
std::string name("Luna");
Log(name);
Log(std::string("Star"));
Log("Seokjoon");
// L-Value std::string를 emplace로 COPY (기존과 동일)
// R-Value를 emplace로 MOVE
// std::string를 item에서 임시로 만드는 것이 아니라
// multiset 안에다가 직접 생성함
하지만 std::string가 아닌 Indirect로 값을 받아야 할 경우가 있다면 ???
Effective Modern C++ Study
C++ Korea35
std::string GetItemFromTable(int idx);
void Log(int idx)
{
History.emplace(GetItemFromTable( ));
}
Log(22);
short s = 22;
Log(s);
// Call int overload
// Compile Error :
// can’t convert argument
// ‘short’ to std::string ctor
Universal Reference Overload 함수는 C++에서 가장 탐욕스러운 함수이다. (닥치는 대로 호로록)
• Instantiation of template (자세한 설명 생략)
• Overload Resolution Rule (자세한 설명 생략)
(위 2가지에 대해서 모른다면 검색해서 알아 보도록… Right Now !!!)
• Parameter가 int인 경우 정확히 int Overload 함수를 실행하지만,
• short인 경우는 T&&을 이용하여 Instantiation이 가능하다.
• Overload Resolution Rule에 의해서 template 함수가 호출되며,
Compile Error를 발생시킨다.
해결방법은 ? Perfect Forwarding Constructor (라고는 하는데 이번 item에서는 해결이 안된다.)
Effective Modern C++ Study
C++ Korea36
class Item {
public:
template<typename T>
explicit Item(T&& data) // Perfect Forwarding ctor
: value(std::forward<T>(data)) {}
explicit Item(int idx) // int ctor
: value(GetItemFromTable(idx)) {}
private:
std::string value;
};
• 하지만, int를 제외한 나머지 타입 (std::size_t, short, long …)에 대해서는 Universal Reference Constructor가 호출
• 심지어 생성자에 다른 Item 개체를 넣어도 Universal Reference Constructor 생성자가 ???
아 왜 ?
Effective Modern C++ Study
C++ Korea37
Item ME("Luna");
auto CloneofME(ME);
Item(const Item& SRC); // Copy ctor (Compiler-generated)
Item(Item&& SRC); // Move ctor (Compiler-generated)
explicit Item(Item& ) // Instantiated from Perfect Forwarding template
: value(std::forward<Item&>(data)) {}
• Overload Resolution Rule에 따라 본다면, 뭐가 가장 parameter에 똑같이 매칭될까 ?
• 그럼 해결 방법은 ?
Compiler는 C++의 Rule을 반드시 지키도록 맹세하였다. (융통성 없는 놈하고는…)
const Item ME("Luna"); // Object is now const
auto CloneofME(ME);
Effective Modern C++ Study
C++ Korea38
class ItemEx : public Item {
public:
ItemEx(const ItemEx& item) // Copy ctor
: Item(item) {} // Calls base class forward ctor
ItemEx(ItemEx&& item) // Move ctor
: Item(std::move(item)) {} // Calls base class forward ctor
};
• Derived Class에서 Base Class로 Item이 아닌 ItemEx로 전달하기 때문이다.
Effective Modern C++ Study
C++ Korea39
• Universal Reference를 Overload하면 뭘 상상하든 그 이상으로
훨씬 더 자주 맨날맨날 허구언날 시도때도 없이
Universal Reference Overload가 호출된다.
• Perfect Forwarding Constructor도 마찬가지다. 아니 이놈은 더하다.
non-const L-Value와의 궁합이 COPY Constructor보다 더 잘 맞고,
Derived class의 COPY, MOVE Constructor의 호출도 가로채버린다.
• 그냥 Universal Reference Overload 와 Perfect Forwarding Constructor를 쓰지마라.
http://devluna.blogspot.kr/2015/03/item-26-universal-reference.html
icysword77@gmail.com

More Related Content

What's hot

Modern C++ 프로그래머를 위한 CPP11/14 핵심
Modern C++ 프로그래머를 위한 CPP11/14 핵심Modern C++ 프로그래머를 위한 CPP11/14 핵심
Modern C++ 프로그래머를 위한 CPP11/14 핵심
흥배 최
 
NDC14 - 사례로 배우는 디스어셈블리 디버깅
NDC14 - 사례로 배우는 디스어셈블리 디버깅NDC14 - 사례로 배우는 디스어셈블리 디버깅
NDC14 - 사례로 배우는 디스어셈블리 디버깅
Seungjae Lee
 
Effective Modern C++ 勉強会 Item26
Effective Modern C++ 勉強会 Item26Effective Modern C++ 勉強会 Item26
Effective Modern C++ 勉強会 Item26
Akihiro Nishimura
 
[0410 박민근] 기술 면접시 자주 나오는 문제들
[0410 박민근] 기술 면접시 자주 나오는 문제들[0410 박민근] 기술 면접시 자주 나오는 문제들
[0410 박민근] 기술 면접시 자주 나오는 문제들
MinGeun Park
 
Clean code: meaningful Name
Clean code: meaningful NameClean code: meaningful Name
Clean code: meaningful Name
nahid035
 
개발을잘하고싶어요-네이버랩스 송기선님
개발을잘하고싶어요-네이버랩스 송기선님개발을잘하고싶어요-네이버랩스 송기선님
개발을잘하고싶어요-네이버랩스 송기선님
NAVER D2
 

What's hot (20)

OOP in C++
OOP in C++OOP in C++
OOP in C++
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
Modern C++ 프로그래머를 위한 CPP11/14 핵심
Modern C++ 프로그래머를 위한 CPP11/14 핵심Modern C++ 프로그래머를 위한 CPP11/14 핵심
Modern C++ 프로그래머를 위한 CPP11/14 핵심
 
[C++ Korea 3rd Seminar] 새 C++은 새 Visual Studio에, 좌충우돌 마이그레이션 이야기
[C++ Korea 3rd Seminar] 새 C++은 새 Visual Studio에, 좌충우돌 마이그레이션 이야기[C++ Korea 3rd Seminar] 새 C++은 새 Visual Studio에, 좌충우돌 마이그레이션 이야기
[C++ Korea 3rd Seminar] 새 C++은 새 Visual Studio에, 좌충우돌 마이그레이션 이야기
 
06. operator overloading
06. operator overloading06. operator overloading
06. operator overloading
 
NDC14 - 사례로 배우는 디스어셈블리 디버깅
NDC14 - 사례로 배우는 디스어셈블리 디버깅NDC14 - 사례로 배우는 디스어셈블리 디버깅
NDC14 - 사례로 배우는 디스어셈블리 디버깅
 
Intro to c++
Intro to c++Intro to c++
Intro to c++
 
C++11: Rvalue References, Move Semantics, Perfect Forwarding
C++11: Rvalue References, Move Semantics, Perfect ForwardingC++11: Rvalue References, Move Semantics, Perfect Forwarding
C++11: Rvalue References, Move Semantics, Perfect Forwarding
 
Hot C++: Rvalue References And Move Semantics
Hot C++: Rvalue References And Move SemanticsHot C++: Rvalue References And Move Semantics
Hot C++: Rvalue References And Move Semantics
 
C++コミュニティーの中心でC++をDISる
C++コミュニティーの中心でC++をDISるC++コミュニティーの中心でC++をDISる
C++コミュニティーの中心でC++をDISる
 
Effective Modern C++ 勉強会 Item26
Effective Modern C++ 勉強会 Item26Effective Modern C++ 勉強会 Item26
Effective Modern C++ 勉強会 Item26
 
Modern C++의 타입 추론과 람다, 컨셉
Modern C++의 타입 추론과 람다, 컨셉Modern C++의 타입 추론과 람다, 컨셉
Modern C++의 타입 추론과 람다, 컨셉
 
[0410 박민근] 기술 면접시 자주 나오는 문제들
[0410 박민근] 기술 면접시 자주 나오는 문제들[0410 박민근] 기술 면접시 자주 나오는 문제들
[0410 박민근] 기술 면접시 자주 나오는 문제들
 
텐서플로우 설치도 했고 튜토리얼도 봤고 기초 예제도 짜봤다면 TensorFlow KR Meetup 2016
텐서플로우 설치도 했고 튜토리얼도 봤고 기초 예제도 짜봤다면 TensorFlow KR Meetup 2016텐서플로우 설치도 했고 튜토리얼도 봤고 기초 예제도 짜봤다면 TensorFlow KR Meetup 2016
텐서플로우 설치도 했고 튜토리얼도 봤고 기초 예제도 짜봤다면 TensorFlow KR Meetup 2016
 
Top C Language Interview Questions and Answer
Top C Language Interview Questions and AnswerTop C Language Interview Questions and Answer
Top C Language Interview Questions and Answer
 
우아하게 준비하는 테스트와 리팩토링 - PyCon Korea 2018
우아하게 준비하는 테스트와 리팩토링 - PyCon Korea 2018우아하게 준비하는 테스트와 리팩토링 - PyCon Korea 2018
우아하게 준비하는 테스트와 리팩토링 - PyCon Korea 2018
 
NDC11_슈퍼클래스
NDC11_슈퍼클래스NDC11_슈퍼클래스
NDC11_슈퍼클래스
 
Clean code: meaningful Name
Clean code: meaningful NameClean code: meaningful Name
Clean code: meaningful Name
 
개발을잘하고싶어요-네이버랩스 송기선님
개발을잘하고싶어요-네이버랩스 송기선님개발을잘하고싶어요-네이버랩스 송기선님
개발을잘하고싶어요-네이버랩스 송기선님
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by Example
 

Similar to [C++ Korea] Effective Modern C++ Study item 24-26

[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
 

Similar to [C++ Korea] Effective Modern C++ Study item 24-26 (20)

모던 C++ 정리
모던 C++ 정리모던 C++ 정리
모던 C++ 정리
 
[C++ Korea] Effective Modern C++ Study item 31-33
[C++ Korea] Effective Modern C++ Study item 31-33[C++ Korea] Effective Modern C++ Study item 31-33
[C++ Korea] Effective Modern C++ Study item 31-33
 
C++20 Key Features Summary
C++20 Key Features SummaryC++20 Key Features Summary
C++20 Key Features Summary
 
[C++ Korea] C++ 메모리 모델과 atomic 타입 연산들
[C++ Korea] C++ 메모리 모델과 atomic 타입 연산들[C++ Korea] C++ 메모리 모델과 atomic 타입 연산들
[C++ Korea] C++ 메모리 모델과 atomic 타입 연산들
 
[NDC2016] TERA 서버의 Modern C++ 활용기
[NDC2016] TERA 서버의 Modern C++ 활용기[NDC2016] TERA 서버의 Modern C++ 활용기
[NDC2016] TERA 서버의 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
 
불어오는 변화의 바람, 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
 
Changes in c++0x
Changes in c++0xChanges in c++0x
Changes in c++0x
 
[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++ 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...
 
About Visual C++ 10
About  Visual C++ 10About  Visual C++ 10
About Visual C++ 10
 
Visual studio 2010
Visual studio 2010Visual studio 2010
Visual studio 2010
 
초보를 위한 C++11
초보를 위한 C++11초보를 위한 C++11
초보를 위한 C++11
 
2013 C++ Study For Students #1
2013 C++ Study For Students #12013 C++ Study For Students #1
2013 C++ Study For Students #1
 
[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...
 
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
 
강의자료 2
강의자료 2강의자료 2
강의자료 2
 
스위프트 성능 이해하기
스위프트 성능 이해하기스위프트 성능 이해하기
스위프트 성능 이해하기
 
C++ 타입 추론
C++ 타입 추론C++ 타입 추론
C++ 타입 추론
 
C++ Advanced 강의 5주차
C++ Advanced 강의 5주차C++ Advanced 강의 5주차
C++ Advanced 강의 5주차
 

More from Seok-joon Yun

[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4
[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4
[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4
Seok-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 24-26

  • 1. Effective Modern C++ Study C++ Korea
  • 2.
  • 3. Effective Modern C++ Study C++ Korea3 불필요한 복사를 줄이기 위해 레퍼런스로 받음. R-Value는 받을 수 없음.
  • 4. Effective Modern C++ Study C++ Korea4
  • 5. Effective Modern C++ Study C++ Korea w의 타입은 Widget& w의 타입은 Widget&&
  • 6. Effective Modern C++ Study C++ Korea6 • R-Value Reference • Universal Reference std::vector<T>의 T는 param과 독립적.
  • 7. Effective Modern C++ Study C++ Korea7 • Universal Reference 아님. • R-Value만 받을 수 있다. • 타입 추론이 발생 하지 않는다.
  • 8. Effective Modern C++ Study C++ Korea8
  • 9. Effective Modern C++ Study C++ Korea9
  • 10.
  • 11. Effective Modern C++ Study C++ Korea11
  • 12. Effective Modern C++ Study C++ Korea12
  • 13. Effective Modern C++ Study C++ Korea13
  • 14. Effective Modern C++ Study C++ Korea14
  • 15. Effective Modern C++ Study C++ Korea15
  • 16. Effective Modern C++ Study C++ Korea16 //지역변수 n이 w.setName으로 이동
  • 17. Effective Modern C++ Study C++ Korea17
  • 18. Effective Modern C++ Study C++ Korea18
  • 19. Effective Modern C++ Study C++ Korea19
  • 20. Effective Modern C++ Study C++ Korea20
  • 21. Effective Modern C++ Study C++ Korea21
  • 22. Effective Modern C++ Study C++ Korea22
  • 23. Effective Modern C++ Study C++ Korea23
  • 24. Effective Modern C++ Study C++ Korea24
  • 25. Effective Modern C++ Study C++ Korea25
  • 26. Effective Modern C++ Study C++ Korea26
  • 27. Effective Modern C++ Study C++ Korea27 RVO
  • 28. Effective Modern C++ Study C++ Korea28 A : 조건 2에 부합하지 않음
  • 29. Effective Modern C++ Study C++ Korea29
  • 30. Effective Modern C++ Study C++ Korea30
  • 31. Effective Modern C++ Study C++ Korea31
  • 32.
  • 33. Effective Modern C++ Study C++ Korea33 std::multiset<std::string> History; // Global Log History void Log(const std::string& item) { History.emplace(item); } std::string name("Luna"); Log(name); Log(std::string("Star")); Log("Seokjoon"); // Parameter로 name이라는 변수가 사용됨. // L-Value가 emplace로 COPY // Parameter로 R-Value가 전달되었지만, // item이 L-Value라서 결국 emplace로 COPY // Parameter로 R-Value가 전달되었지만, // 임시로 std::string 개체가 만들어져서 결국 emplace로 COPY Universal Reference + std::forward 면 efficient하게 할 수 있다.
  • 34. Effective Modern C++ Study C++ Korea34 std::multiset<std::string> History; // Global Log History template<typename T> void Log(T&& item) { History.emplace(std::forward<T>(item)); } std::string name("Luna"); Log(name); Log(std::string("Star")); Log("Seokjoon"); // L-Value std::string를 emplace로 COPY (기존과 동일) // R-Value를 emplace로 MOVE // std::string를 item에서 임시로 만드는 것이 아니라 // multiset 안에다가 직접 생성함 하지만 std::string가 아닌 Indirect로 값을 받아야 할 경우가 있다면 ???
  • 35. Effective Modern C++ Study C++ Korea35 std::string GetItemFromTable(int idx); void Log(int idx) { History.emplace(GetItemFromTable( )); } Log(22); short s = 22; Log(s); // Call int overload // Compile Error : // can’t convert argument // ‘short’ to std::string ctor Universal Reference Overload 함수는 C++에서 가장 탐욕스러운 함수이다. (닥치는 대로 호로록) • Instantiation of template (자세한 설명 생략) • Overload Resolution Rule (자세한 설명 생략) (위 2가지에 대해서 모른다면 검색해서 알아 보도록… Right Now !!!) • Parameter가 int인 경우 정확히 int Overload 함수를 실행하지만, • short인 경우는 T&&을 이용하여 Instantiation이 가능하다. • Overload Resolution Rule에 의해서 template 함수가 호출되며, Compile Error를 발생시킨다. 해결방법은 ? Perfect Forwarding Constructor (라고는 하는데 이번 item에서는 해결이 안된다.)
  • 36. Effective Modern C++ Study C++ Korea36 class Item { public: template<typename T> explicit Item(T&& data) // Perfect Forwarding ctor : value(std::forward<T>(data)) {} explicit Item(int idx) // int ctor : value(GetItemFromTable(idx)) {} private: std::string value; }; • 하지만, int를 제외한 나머지 타입 (std::size_t, short, long …)에 대해서는 Universal Reference Constructor가 호출 • 심지어 생성자에 다른 Item 개체를 넣어도 Universal Reference Constructor 생성자가 ??? 아 왜 ?
  • 37. Effective Modern C++ Study C++ Korea37 Item ME("Luna"); auto CloneofME(ME); Item(const Item& SRC); // Copy ctor (Compiler-generated) Item(Item&& SRC); // Move ctor (Compiler-generated) explicit Item(Item& ) // Instantiated from Perfect Forwarding template : value(std::forward<Item&>(data)) {} • Overload Resolution Rule에 따라 본다면, 뭐가 가장 parameter에 똑같이 매칭될까 ? • 그럼 해결 방법은 ? Compiler는 C++의 Rule을 반드시 지키도록 맹세하였다. (융통성 없는 놈하고는…) const Item ME("Luna"); // Object is now const auto CloneofME(ME);
  • 38. Effective Modern C++ Study C++ Korea38 class ItemEx : public Item { public: ItemEx(const ItemEx& item) // Copy ctor : Item(item) {} // Calls base class forward ctor ItemEx(ItemEx&& item) // Move ctor : Item(std::move(item)) {} // Calls base class forward ctor }; • Derived Class에서 Base Class로 Item이 아닌 ItemEx로 전달하기 때문이다.
  • 39. Effective Modern C++ Study C++ Korea39 • Universal Reference를 Overload하면 뭘 상상하든 그 이상으로 훨씬 더 자주 맨날맨날 허구언날 시도때도 없이 Universal Reference Overload가 호출된다. • Perfect Forwarding Constructor도 마찬가지다. 아니 이놈은 더하다. non-const L-Value와의 궁합이 COPY Constructor보다 더 잘 맞고, Derived class의 COPY, MOVE Constructor의 호출도 가로채버린다. • 그냥 Universal Reference Overload 와 Perfect Forwarding Constructor를 쓰지마라.