SlideShare a Scribd company logo
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 공식 팀 블로그

More Related Content

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

What's hot (20)

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

Similar to Changes in c++0x (20)

PDF
C++ Advanced 강의 5주차
PDF
초보를 위한 C++11
PPTX
What’s new in c++11
PPTX
포트폴리오에서 사용한 모던 C++
PPTX
NHNNEXT 개경프14 Subway Rocket Team Study 3rd C++
PPTX
불어오는 변화의 바람, From c++98 to c++11, 14
PDF
C++11 1
PDF
7 8 1
PPTX
Effective c++ Chapter1,2
PPT
강의자료3
PPTX
Modern C++의 타입 추론과 람다, 컨셉
PPTX
Effective C++ Chaper 1
PDF
Template at c++
PDF
C++ Advanced 강의 1주차
PPTX
이펙티브 C++ 스터디
PPTX
More Effective C++ 4주차
PPTX
이펙티브 C++ 789 공부
PDF
[143] Modern C++ 무조건 써야 해?
PDF
Effective c++ chapter 1,2 요약
PPTX
PS에 쓸 수 있도록 C++ 입문하기.pptx ㅔ뱆더게ㅠㅐㅓㅔㅂ대ㅓ규ㅔㅐㅓ
C++ Advanced 강의 5주차
초보를 위한 C++11
What’s new in c++11
포트폴리오에서 사용한 모던 C++
NHNNEXT 개경프14 Subway Rocket Team Study 3rd C++
불어오는 변화의 바람, From c++98 to c++11, 14
C++11 1
7 8 1
Effective c++ Chapter1,2
강의자료3
Modern C++의 타입 추론과 람다, 컨셉
Effective C++ Chaper 1
Template at c++
C++ Advanced 강의 1주차
이펙티브 C++ 스터디
More Effective C++ 4주차
이펙티브 C++ 789 공부
[143] Modern C++ 무조건 써야 해?
Effective c++ chapter 1,2 요약
PS에 쓸 수 있도록 C++ 입문하기.pptx ㅔ뱆더게ㅠㅐㅓㅔㅂ대ㅓ규ㅔㅐㅓ
Ad

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와 비슷한 조건 조사를 할 수 있음  컴파일 타임 때 사용  템플릿 프로그래밍에 사용하면 유용하다