NCG Training Day 4 Part-1 (C++11 Introduction and New Keywords)
NCG Training Day 4 Part-1 (C++11 Introduction and New Keywords)
NCG Training Day 4 Part-1 (C++11 Introduction and New Keywords)
Adobe
auto, nullptr
decltype, static_assert
Sequence Container
Associative Container
string
lambda expression
STL Algorithms
for_each
References
Adobe
C++11 Introduction
C++ Dev Bootcamp 2014 Day 4
Adobe
History of C++11
In 1979 Bjarne Stroustrup was doing work for his Ph.D. thesis, he got
opportunity to work on Simula. He liked the language and shortly after
he started to work on C with Classes.
Adobe
Adobe
Why C++11
Adobe
Adobe
Auto
Example:
auto x = 5; // OK: x has type int
const auto *v = &x, u = 6; // OK: v has type const int*, u has type const int
static auto y = 0.0; // OK: y has type double
auto int r; // error: auto is not a storage-class-specifier
auto pX = new auto(1); // allocated type is int
auto x = new auto(a); // allocated type is char, x is of type char*
auto multiply (int x, int y) -> int; // new function syntax
Adobe
Auto
C++03
C++11
map<string,string>::iterator it =
m.begin();
double const param =
config["param"];
singleton& s = singleton::instance();
auto it = m.begin();
auto const param =
config["param"];
auto& s =
singleton::instance();
Adobe
nullptr
Example:
int * pX = nullptr;
int x;
pX = &x;
if(pX==nullptr) //OK
if(x == nullptr) //Error
Adobe
10
rValue references
Adobe
11
Move Constructor
Example:
class MyString {
public:
MyString(MyString& a_MyString) : m_pData(nullptr) {
if(a_MyString.m_pData)
m_pData = new std::string(*a_MyString.m_pData); //Creating new memory and then
copy
}
MyString(MyString&& a_MyString) {
m_pData = a_MyString.m_pData; //no new memory or copy, simply move
a_MyString.m_pData=nullptr;
}
private:
std::string* m_pData;
};
Adobe
12
Move constructor
Adobe
13
decltype
Example:
int i;
struct A { double x; };
const A* a = new A();
decltype(i) x2; // type is int
decltype(a->x) x3; // type is double
decltype((a->x)) x4 = x3; // type is const double&
Adobe
14
decltype
More example:
auto c = 0; // c has type int
auto d = c; // d has type int
decltype(c) e; // e has type int, the type of the entity named by c
decltype((c)) f = c; // f has type int&, because (c) is an lvalue
decltype(0) g; // g has type int, because 0 is an rvalue
const int&& foo();
decltype(foo()) x1 = i; // type is const int&&
auto multiply (int x, int y) -> decltype(x * y);
template <typename T1, typename T2> // generic return type
auto add(T1 a, T2 b) -> decltype(a + b) {
return a + b;
}
Adobe
15
static_assert
Example:
template <typename T>
void print(T a) {
static_assert(sizeof(T) == 4, "Unsupported Type, size should be 4");
cout << a << endl;
cout << b << endl;
}
void TestStaticAssert() {
print(1);
print("test");
print('a'); // "Unsupported Type, size should be 4"
}
Adobe
16
Adobe