SlideShare une entreprise Scribd logo
1  sur  18
Changes in C++11
전상연
C++11
 오랫동안 C++0x로 알려졌었다.
 하지만 2010년이 되어버렸긔…
 0x는 16진수라 2015년까진 나올꺼란 드립이 나옴
 올해 스펙이 확정되면서 C++11로 확정
 많은 변화가 있지만
 오늘 살펴볼 내용은
 http://www.softwarequalityconnection.com/2011/06/th
e-biggest-changes-in-c11-and-why-you-should-care/
 를 정리한 내용입니다.
C++11
 New Algorithms
 New Container Classes
 Atomic Operations
 Type Traits
 Regular Expressions
 New Smart Pointers
 Multithreading Library
 TR1에 추가된 내용들이 대부분.
 Boost에 상당부분 구현되어있다.
 오늘은 Core한 부분을 보겠습니다.
Lambda Expressions
 [capture](parameters)->return-type {body}
 함수 안에 함수를 내장 할 수 있다.
 Functor 를 암시적으로 만들 수 있음
int main()
{
char s[]="Hello World!";
int Uppercase = 0; //modified by the lambda
for_each(s, s+sizeof(s), [&Uppercase] (char c) {
if (isupper(c))
Uppercase++;
});
cout<< Uppercase<<" uppercase letters in: "<< s<<endl;
}
Automatic Type Deduction and decltype
 vector<int>::const_iterator ci = vi.begin();
 컴파일러는 사실 다 알고 있다.
 auto ci = vi.begin();
 const vector<int> vi;
// 실제로 vi.begin()이 호출되지는 않는다.
typedef decltype (vi.begin()) CIT;
CIT another_const_iterator;
Uniform Initialization Syntax
 초기화는 { }로 대동단결
 C c {0,0}; //C++11 only. Equivalent to: C c(0,0);
 int* a = new int[3] { 1, 2, 0 };
 class X {
int a[4];
public:
X() : a{1,2,3,4} {} //C++11, member array initializer
};
 vector<string> vs={ "first", "second", "third"};
 map singers = { {"Lady Gaga", "+1 (212) 555-7890"},
{"Beyonce Knowles", "+1 (212) 555-0987"} };
 class C {
int a=7; //C++11 only
public:
C();
};
Deleted and Defaulted Functions
 class X {
X& operator=(const X&) = delete; // Disallow copying
X(const X&) = delete;
};
 X a;
X b(a); // compilation error!
 class Y {
Y& operator=(const Y&) = default; // default copy
semantics
Y(const Y&) = default;
}
 기본적인 동작을 하는 대입 연산자와 복사 생성자는 코드
를 구현할 필요가 없이 컴파일러에서 알아서 만들어준다.
nullptr
 char* p = nullptr;
Delegating Constructors
 생성자에서 다른 생성자를 부를 수 있다
 C++98
class X {
int a;
validate(int x) {
if (0<x && x<=max) a=x; else throw bad_X(x);
}
public:
X(int x) { validate(x); }
X() { validate(42); }
X(string s) { int x = lexical_cast<int>(s); validate(x); }
};
 C++11
class X {
int a;
public:
X(int x) { if (0<x && x<=max) a=x; else throw bad_X(x); }
X() :X{42} { }
X(string s) :X{lexical_cast<int>(s)} { }
};
Rvalue References
 C++의 Reference(&)는 Lvalue reference다.
 A = B;
 A – Lvalue / B – Rvalue
 Rvalue reference - &&으로 표기
 임시 객체를 바인딩할 수 있다
 A& a_ref3 = A(); // Error!
A&& a_ref4 = A(); // Ok
Move Semantics
 C++03까지의 swap
 template <class T> swap(T& a, T& b)
{
T tmp(a); // now we have two copies of a
a = b; // now we have two copies of b
b = tmp; // now we have two copies of tmp
(aka a)
}
 vector 같은 container는 멤버함수로 swap을 구현한
다음에 swap에 대해서 템플릿 특화를 해야 했다
 swap(vector<T>& left, vector<T>& right)
{ left.swap(right); }
 직접 만드는 클래스도 비슷하게 구현할 수 있지만…
 어떤 알고리즘에서 쓰일 줄 알고? 다 구현해야 하나?
C++11의 swap
 template <class T> swap(T& a, T& b)
{
T tmp(std::move(a));
a = std::move(b);
b = std::move(tmp);
}
 std::move 는 값을 반환하는데, 원본의 값이 유지될
필요가 없다
 a의 값은 tmp로 넘어가고, b의 값은 a로 넘어가고, tmp의
값은 다시 b로 넘어간다. 복사가 아니다.
move를 지원하기 위해서는
 class에 move contructor와 move assignment operator를 구현해야 한다.
 class Derived
: public Base
{
std::vector<int> vec;
std::string name;
public:
// …
// move semantics
Derived(Derived&& x) // rvalues bind here
: Base(std::move(x)),
vec(std::move(x.vec)),
name(std::move(x.name))
{ }
Derived& operator=(Derived&& x) // rvalues bind here
{
Base::operator=(std::move(x));
vec = std::move(x.vec);
name = std::move(x.name);
return *this;
}
// …
};
복사는 불가해도 이동은 가능한 타입이 가능
 fstream
 unique_ptr
 auto_ptr이 사라지고 새로 들어감
 non-shared, non-copiable ownership
 기타 등등
Perfect Forwarding
 Template 함수에서 인자로 넘어왔을 때
 Lvalue로 넘어온건 copy하자
 Rvalue로 넘어온건 move하자
 Constness는 유지하자
 class Widget {
string name1;
string name2;
public:
template<typename T1, typename T2>
Widget(T1&& t1, T2&& t2)
: name1(std::forward<T1>(t1))
, name2(std::forward<T2>(t2))
{ }
};
 string GetStr() { return string("456"); }
 string a="123";
Widget b(a, GetStr());
성능 비교
 http://vsts2010.tistory.com/483
static_assert
 #include <iostream>
using namespace std;
int main()
{
static_assert( sizeof(int) == 4, "not int size 4" );
return 0;
}
 assert와 비슷한 조건 조사를 할 수 있음
 컴파일 타임 때 사용
 템플릿 프로그래밍에 사용하면 유용하다
참고 사이트
 http://vsts2010.tistory.com/ VS2010 공식 팀 블로그

Contenu connexe

Tendances

[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
 
[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
[C++ Korea] Effective Modern C++ Study item 24-26Seok-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 ...
Effective Modern C++ MVA item 18 Use std::unique_ptr for exclusive-ownership ...Seok-joon Yun
 
[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 - 3Chris Ohk
 
Modern C++ 프로그래머를 위한 CPP11/14 핵심
Modern C++ 프로그래머를 위한 CPP11/14 핵심Modern C++ 프로그래머를 위한 CPP11/14 핵심
Modern C++ 프로그래머를 위한 CPP11/14 핵심흥배 최
 
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기Chris Ohk
 
[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 신촌 study
[C++ korea] effective modern c++ study item 17 19 신촌 studySeok-joon Yun
 
[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++11 이야기
프로그래밍 대회: C++11 이야기프로그래밍 대회: C++11 이야기
프로그래밍 대회: C++11 이야기Jongwook Choi
 
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
 
Modern effective c++ 항목 3
Modern effective c++ 항목 3Modern effective c++ 항목 3
Modern effective c++ 항목 3ssuser7c5a40
 
C++ 11 에 대해서 쉽게 알아봅시다 1부
C++ 11 에 대해서 쉽게 알아봅시다 1부C++ 11 에 대해서 쉽게 알아봅시다 1부
C++ 11 에 대해서 쉽게 알아봅시다 1부Gwangwhi Mah
 
2013 C++ Study For Students #1
2013 C++ Study For Students #12013 C++ Study For Students #1
2013 C++ Study For Students #1Chris Ohk
 
C++ 타입 추론
C++ 타입 추론C++ 타입 추론
C++ 타입 추론Huey Park
 
[Pl in c++] 9. 다형성
[Pl in c++] 9. 다형성[Pl in c++] 9. 다형성
[Pl in c++] 9. 다형성MinGeun Park
 
7가지 동시성 모델 - 3장. 함수형 프로그래밍
7가지 동시성 모델 - 3장. 함수형 프로그래밍7가지 동시성 모델 - 3장. 함수형 프로그래밍
7가지 동시성 모델 - 3장. 함수형 프로그래밍Hyunsoo Jung
 
모던 C++ 정리
모던 C++ 정리모던 C++ 정리
모던 C++ 정리Hansol Kang
 

Tendances (20)

[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...
 
[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
[C++ Korea] Effective Modern C++ Study item 24-26
 
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 ...
Effective Modern C++ MVA item 18 Use std::unique_ptr for exclusive-ownership ...
 
C++11
C++11C++11
C++11
 
[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
 
Modern C++ 프로그래머를 위한 CPP11/14 핵심
Modern C++ 프로그래머를 위한 CPP11/14 핵심Modern C++ 프로그래머를 위한 CPP11/14 핵심
Modern C++ 프로그래머를 위한 CPP11/14 핵심
 
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
 
[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 신촌 study
[C++ korea] effective modern c++ study item 17 19 신촌 study
 
[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++11 이야기
프로그래밍 대회: C++11 이야기프로그래밍 대회: C++11 이야기
프로그래밍 대회: C++11 이야기
 
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
 
Modern effective c++ 항목 3
Modern effective c++ 항목 3Modern effective c++ 항목 3
Modern effective c++ 항목 3
 
C++ 11 에 대해서 쉽게 알아봅시다 1부
C++ 11 에 대해서 쉽게 알아봅시다 1부C++ 11 에 대해서 쉽게 알아봅시다 1부
C++ 11 에 대해서 쉽게 알아봅시다 1부
 
2013 C++ Study For Students #1
2013 C++ Study For Students #12013 C++ Study For Students #1
2013 C++ Study For Students #1
 
C++ 타입 추론
C++ 타입 추론C++ 타입 추론
C++ 타입 추론
 
함수
함수함수
함수
 
[Pl in c++] 9. 다형성
[Pl in c++] 9. 다형성[Pl in c++] 9. 다형성
[Pl in c++] 9. 다형성
 
6 swift 고급함수
6 swift 고급함수6 swift 고급함수
6 swift 고급함수
 
7가지 동시성 모델 - 3장. 함수형 프로그래밍
7가지 동시성 모델 - 3장. 함수형 프로그래밍7가지 동시성 모델 - 3장. 함수형 프로그래밍
7가지 동시성 모델 - 3장. 함수형 프로그래밍
 
모던 C++ 정리
모던 C++ 정리모던 C++ 정리
모던 C++ 정리
 

Similaire à Changes in c++0x

Modern C++의 타입 추론과 람다, 컨셉
Modern C++의 타입 추론과 람다, 컨셉Modern C++의 타입 추론과 람다, 컨셉
Modern C++의 타입 추론과 람다, 컨셉HyunJoon Park
 
About Visual C++ 10
About  Visual C++ 10About  Visual C++ 10
About Visual C++ 10흥배 최
 
포트폴리오에서 사용한 모던 C++
포트폴리오에서 사용한 모던 C++포트폴리오에서 사용한 모던 C++
포트폴리오에서 사용한 모던 C++KWANGIL KIM
 
불어오는 변화의 바람, 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 명신 김
 
Ai C#세미나
Ai C#세미나Ai C#세미나
Ai C#세미나Astin Choi
 
C++20 Key Features Summary
C++20 Key Features SummaryC++20 Key Features Summary
C++20 Key Features SummaryChris Ohk
 
나에 첫번째 자바8 람다식 지앤선
나에 첫번째 자바8 람다식   지앤선나에 첫번째 자바8 람다식   지앤선
나에 첫번째 자바8 람다식 지앤선daewon jeong
 
Boost 라이브리와 C++11
Boost 라이브리와 C++11Boost 라이브리와 C++11
Boost 라이브리와 C++11OnGameServer
 
[143] Modern C++ 무조건 써야 해?
[143] Modern C++ 무조건 써야 해?[143] Modern C++ 무조건 써야 해?
[143] Modern C++ 무조건 써야 해?NAVER D2
 
카사 공개세미나1회 W.E.L.C.
카사 공개세미나1회  W.E.L.C.카사 공개세미나1회  W.E.L.C.
카사 공개세미나1회 W.E.L.C.Ryan Park
 
[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)
[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)
[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)Sang Don Kim
 
C++ 프로그래밍 2014-2018년 기말시험 기출문제
C++ 프로그래밍 2014-2018년 기말시험 기출문제C++ 프로그래밍 2014-2018년 기말시험 기출문제
C++ 프로그래밍 2014-2018년 기말시험 기출문제Lee Sang-Ho
 
Api design for c++ 6장
Api design for c++ 6장Api design for c++ 6장
Api design for c++ 6장Ji Hun Kim
 
Lambda 란 무엇인가
Lambda 란 무엇인가Lambda 란 무엇인가
Lambda 란 무엇인가Vong Sik Kong
 
[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-33Seok-joon Yun
 
More effective c++ chapter1 2_dcshin
More effective c++ chapter1 2_dcshinMore effective c++ chapter1 2_dcshin
More effective c++ chapter1 2_dcshinDong Chan Shin
 
Effective c++ chapter1 2_dcshin
Effective c++ chapter1 2_dcshinEffective c++ chapter1 2_dcshin
Effective c++ chapter1 2_dcshinDong Chan Shin
 

Similaire à Changes in c++0x (20)

Modern C++의 타입 추론과 람다, 컨셉
Modern C++의 타입 추론과 람다, 컨셉Modern C++의 타입 추론과 람다, 컨셉
Modern C++의 타입 추론과 람다, 컨셉
 
About Visual C++ 10
About  Visual C++ 10About  Visual C++ 10
About Visual C++ 10
 
포트폴리오에서 사용한 모던 C++
포트폴리오에서 사용한 모던 C++포트폴리오에서 사용한 모던 C++
포트폴리오에서 사용한 모던 C++
 
불어오는 변화의 바람, 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
 
Ai C#세미나
Ai C#세미나Ai C#세미나
Ai C#세미나
 
C++20 Key Features Summary
C++20 Key Features SummaryC++20 Key Features Summary
C++20 Key Features Summary
 
함수적 사고 2장
함수적 사고 2장함수적 사고 2장
함수적 사고 2장
 
나에 첫번째 자바8 람다식 지앤선
나에 첫번째 자바8 람다식   지앤선나에 첫번째 자바8 람다식   지앤선
나에 첫번째 자바8 람다식 지앤선
 
Boost 라이브리와 C++11
Boost 라이브리와 C++11Boost 라이브리와 C++11
Boost 라이브리와 C++11
 
[143] Modern C++ 무조건 써야 해?
[143] Modern C++ 무조건 써야 해?[143] Modern C++ 무조건 써야 해?
[143] Modern C++ 무조건 써야 해?
 
카사 공개세미나1회 W.E.L.C.
카사 공개세미나1회  W.E.L.C.카사 공개세미나1회  W.E.L.C.
카사 공개세미나1회 W.E.L.C.
 
[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)
[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)
[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)
 
강의자료 2
강의자료 2강의자료 2
강의자료 2
 
C++ 프로그래밍 2014-2018년 기말시험 기출문제
C++ 프로그래밍 2014-2018년 기말시험 기출문제C++ 프로그래밍 2014-2018년 기말시험 기출문제
C++ 프로그래밍 2014-2018년 기말시험 기출문제
 
06장 함수
06장 함수06장 함수
06장 함수
 
Api design for c++ 6장
Api design for c++ 6장Api design for c++ 6장
Api design for c++ 6장
 
Lambda 란 무엇인가
Lambda 란 무엇인가Lambda 란 무엇인가
Lambda 란 무엇인가
 
[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
 
More effective c++ chapter1 2_dcshin
More effective c++ chapter1 2_dcshinMore effective c++ chapter1 2_dcshin
More effective c++ chapter1 2_dcshin
 
Effective c++ chapter1 2_dcshin
Effective c++ chapter1 2_dcshinEffective c++ chapter1 2_dcshin
Effective c++ chapter1 2_dcshin
 

Changes in c++0x

  • 2. C++11  오랫동안 C++0x로 알려졌었다.  하지만 2010년이 되어버렸긔…  0x는 16진수라 2015년까진 나올꺼란 드립이 나옴  올해 스펙이 확정되면서 C++11로 확정  많은 변화가 있지만  오늘 살펴볼 내용은  http://www.softwarequalityconnection.com/2011/06/th e-biggest-changes-in-c11-and-why-you-should-care/  를 정리한 내용입니다.
  • 3. C++11  New Algorithms  New Container Classes  Atomic Operations  Type Traits  Regular Expressions  New Smart Pointers  Multithreading Library  TR1에 추가된 내용들이 대부분.  Boost에 상당부분 구현되어있다.  오늘은 Core한 부분을 보겠습니다.
  • 4. Lambda Expressions  [capture](parameters)->return-type {body}  함수 안에 함수를 내장 할 수 있다.  Functor 를 암시적으로 만들 수 있음 int main() { char s[]="Hello World!"; int Uppercase = 0; //modified by the lambda for_each(s, s+sizeof(s), [&Uppercase] (char c) { if (isupper(c)) Uppercase++; }); cout<< Uppercase<<" uppercase letters in: "<< s<<endl; }
  • 5. Automatic Type Deduction and decltype  vector<int>::const_iterator ci = vi.begin();  컴파일러는 사실 다 알고 있다.  auto ci = vi.begin();  const vector<int> vi; // 실제로 vi.begin()이 호출되지는 않는다. typedef decltype (vi.begin()) CIT; CIT another_const_iterator;
  • 6. Uniform Initialization Syntax  초기화는 { }로 대동단결  C c {0,0}; //C++11 only. Equivalent to: C c(0,0);  int* a = new int[3] { 1, 2, 0 };  class X { int a[4]; public: X() : a{1,2,3,4} {} //C++11, member array initializer };  vector<string> vs={ "first", "second", "third"};  map singers = { {"Lady Gaga", "+1 (212) 555-7890"}, {"Beyonce Knowles", "+1 (212) 555-0987"} };  class C { int a=7; //C++11 only public: C(); };
  • 7. Deleted and Defaulted Functions  class X { X& operator=(const X&) = delete; // Disallow copying X(const X&) = delete; };  X a; X b(a); // compilation error!  class Y { Y& operator=(const Y&) = default; // default copy semantics Y(const Y&) = default; }  기본적인 동작을 하는 대입 연산자와 복사 생성자는 코드 를 구현할 필요가 없이 컴파일러에서 알아서 만들어준다.
  • 8. nullptr  char* p = nullptr;
  • 9. Delegating Constructors  생성자에서 다른 생성자를 부를 수 있다  C++98 class X { int a; validate(int x) { if (0<x && x<=max) a=x; else throw bad_X(x); } public: X(int x) { validate(x); } X() { validate(42); } X(string s) { int x = lexical_cast<int>(s); validate(x); } };  C++11 class X { int a; public: X(int x) { if (0<x && x<=max) a=x; else throw bad_X(x); } X() :X{42} { } X(string s) :X{lexical_cast<int>(s)} { } };
  • 10. Rvalue References  C++의 Reference(&)는 Lvalue reference다.  A = B;  A – Lvalue / B – Rvalue  Rvalue reference - &&으로 표기  임시 객체를 바인딩할 수 있다  A& a_ref3 = A(); // Error! A&& a_ref4 = A(); // Ok
  • 11. Move Semantics  C++03까지의 swap  template <class T> swap(T& a, T& b) { T tmp(a); // now we have two copies of a a = b; // now we have two copies of b b = tmp; // now we have two copies of tmp (aka a) }  vector 같은 container는 멤버함수로 swap을 구현한 다음에 swap에 대해서 템플릿 특화를 해야 했다  swap(vector<T>& left, vector<T>& right) { left.swap(right); }  직접 만드는 클래스도 비슷하게 구현할 수 있지만…  어떤 알고리즘에서 쓰일 줄 알고? 다 구현해야 하나?
  • 12. C++11의 swap  template <class T> swap(T& a, T& b) { T tmp(std::move(a)); a = std::move(b); b = std::move(tmp); }  std::move 는 값을 반환하는데, 원본의 값이 유지될 필요가 없다  a의 값은 tmp로 넘어가고, b의 값은 a로 넘어가고, tmp의 값은 다시 b로 넘어간다. 복사가 아니다.
  • 13. move를 지원하기 위해서는  class에 move contructor와 move assignment operator를 구현해야 한다.  class Derived : public Base { std::vector<int> vec; std::string name; public: // … // move semantics Derived(Derived&& x) // rvalues bind here : Base(std::move(x)), vec(std::move(x.vec)), name(std::move(x.name)) { } Derived& operator=(Derived&& x) // rvalues bind here { Base::operator=(std::move(x)); vec = std::move(x.vec); name = std::move(x.name); return *this; } // … };
  • 14. 복사는 불가해도 이동은 가능한 타입이 가능  fstream  unique_ptr  auto_ptr이 사라지고 새로 들어감  non-shared, non-copiable ownership  기타 등등
  • 15. Perfect Forwarding  Template 함수에서 인자로 넘어왔을 때  Lvalue로 넘어온건 copy하자  Rvalue로 넘어온건 move하자  Constness는 유지하자  class Widget { string name1; string name2; public: template<typename T1, typename T2> Widget(T1&& t1, T2&& t2) : name1(std::forward<T1>(t1)) , name2(std::forward<T2>(t2)) { } };  string GetStr() { return string("456"); }  string a="123"; Widget b(a, GetStr());
  • 17. static_assert  #include <iostream> using namespace std; int main() { static_assert( sizeof(int) == 4, "not int size 4" ); return 0; }  assert와 비슷한 조건 조사를 할 수 있음  컴파일 타임 때 사용  템플릿 프로그래밍에 사용하면 유용하다