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;
}
기본적인 동작을 하는 대입 연산자와 복사 생성자는 코드
를 구현할 필요가 없이 컴파일러에서 알아서 만들어준다.
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
기타 등등
17. static_assert
#include <iostream>
using namespace std;
int main()
{
static_assert( sizeof(int) == 4, "not int size 4" );
return 0;
}
assert와 비슷한 조건 조사를 할 수 있음
컴파일 타임 때 사용
템플릿 프로그래밍에 사용하면 유용하다