c++ 11 features

36
C++ 11 Features What’s new and why we should care (slightly updated presentation)

Upload: jan-rueegg

Post on 12-Apr-2017

661 views

Category:

Engineering


0 download

TRANSCRIPT

Page 1: C++ 11 Features

C++ 11 FeaturesWhat’s new and why we should care(slightly updated presentation)

Page 2: C++ 11 Features

(Very) brief history of C++1979: Bjarne Stroustrup starts “C with

Classes” Classes, few other things

1983: Renamed to C++virtual functions, references, new/delete, ...

1998: ISO C++98First ISO standard

Page 3: C++ 11 Features

(Very) brief history of C++2003: C++03

“Bug fixes”2011: C++11

In the works for almost 10 yearsLots of new language / standard library featuresMost of it supported by all big compilers by now

(VS2012, g++4.8, clang 3.3, Intel 13.0)

Page 4: C++ 11 Features

(Very) brief future of C++2014: C++14

“Bug fixes”Small improvementsStarting to be picked up by compilers

2017: C++17More functionalityLargely undefined

Page 5: C++ 11 Features

Right angle bracketC++std::map<std::string, std::vector<int> > map;C++11std::map<std::string, std::vector<int>> map;

Page 6: C++ 11 Features

autoauto i = 42; // i is an intauto l = 42LL; // l is an long longauto p = new foo(); // p is a foo*

Page 7: C++ 11 Features

auto pointers?int* foo();

// pointer picked up, can be added anywayauto p_bar = foo(); // int*auto *p_baz = foo(); // int*

Page 8: C++ 11 Features

auto references?int& foo();

auto bar = foo(); // int& or int?

Page 9: C++ 11 Features

auto references?int& foo();

auto bar = foo(); // int& or int?

// reference *not* picked upauto bar = foo(); // intauto& baz = foo(); // int&

Page 10: C++ 11 Features

auto constness?const auto foo();

// constness *not* picked upauto bar = foo(); // Abcconst auto baz = foo(); // const Abc

Page 11: C++ 11 Features

auto constness + reference?const int& foo();

auto &bar = foo(); // int& ... ?bar = 3; // Writing to const variable ... ?

Page 12: C++ 11 Features

auto constness + reference?const int& foo();

auto &bar = foo(); // int& ... ?bar = 3; // Writing to const variable ... ?

// Special case, const picked up when const + reference!

auto &bar = foo(); // const int&bar = 3; // Compiler error!

Page 13: C++ 11 Features

auto, general rule:Private, writable

auto foo = bar();Private, not writable:

const auto foo = bar();Shared, not writable:

const auto &foo = bar();Shared, writable

auto &foo = bar();if return value requires copy: same as private

Page 14: C++ 11 Features

autoC++std::map<std::string, std::vector<int>> map;std::map<std::string, std::vector<int>>::iterator it = map.begin();for(it; it != map.end(); ++it){}

C++11std::map<std::string, std::vector<int>> map;auto it = map.begin();for(it; it != map.end(); ++it){}

Page 15: C++ 11 Features

Range-based for loopsC++std::map<std::string, std::vector<int>> map;std::map<std::string, std::vector<int>>::iterator it = map.begin();for(it; it != map.end(); ++it){}

C++11// auto& or const auto& would be more efficient!std::map<std::string, std::vector<int>> map;for (auto element : map){}

Page 16: C++ 11 Features

Range-based for loopsint my_array[5] = {1, 2, 3, 4, 5};// double the value of each element in my_array:for (int &x : my_array) { x *= 2;}

std::vector<int> foo;for(int element : foo){}

Page 17: C++ 11 Features

nullptrvoid foo(int* p) {}void bar(std::shared_ptr<int> p) {}

int* p1 = NULL;int* p2 = nullptr; if(p1 == p2){}

foo(nullptr);bar(nullptr);

bool f = nullptr;int i = nullptr; // error: A native nullptr can only be converted to bool or, using reinterpret_cast, to an integral type

void f(int); //#1void f(char *);//#2

//C++03f(0); //which f is called?

//C++11f(nullptr) //unambiguous, calls #2

Page 18: C++ 11 Features

Override and finalclass B {public: virtual void f(short) {std::cout << "B::f" << std::endl;}};

class D : public B{public: virtual void f(int) {std::cout << "D::f" << std::endl;}};

Page 19: C++ 11 Features

Override and finalclass B {public: virtual void f(int) const {std::cout << "B::f " << std::endl;}};

class D : public B{public: virtual void f(int) {std::cout << "D::f" << std::endl;}};

Page 20: C++ 11 Features

Override and finalclass B {public: virtual void f(short) {std::cout << "B::f" << std::endl;}};

class D : public B{public: virtual void f(int) override {std::cout << "D::f" << std::endl;}};

Page 21: C++ 11 Features

Override and finalclass B {public: virtual void f(short) {std::cout << "B::f" << std::endl;}};

class D : public B{public: virtual void f(int) final {std::cout << "D::f" << std::endl;}};

Page 22: C++ 11 Features

Strongly-typed enumsenum class Options {None, One, All};Options o = Options::All;Type safe

int i = Options::All; // Compiler error!Scoped

Options o = All; // Compiler errorUser-specified underlying type

enum Enum3 : unsigned long {Val1 = 1, Val2};

Page 23: C++ 11 Features

Smart Pointersboost::shared_ptr -> std::shared_ptrboost::unique_ptr -> std::unique_ptrboost::weak_ptr -> std::weak_ptrPretty much the sameFew new features in std pointers

Page 24: C++ 11 Features

Lambdas“Inline functions”[capture](parameters)->return-type {body}Very nice for iteration over data structures

Page 25: C++ 11 Features

Lambdasstd::vector<int> v;v.push_back(1);v.push_back(2);v.push_back(3);

std::for_each(std::begin(v), std::end(v), [](int n){std::cout << n << std::endl;});

auto isOdd = [](int n) {return n%2==1;};auto pos = std::find_if(std::begin(v), std::end(v), isOdd);if(pos != std::end(v)){ std::cout << *pos << std::endl;}

Page 26: C++ 11 Features

static_assertCompile time checksstatic_assert((GREEKPI > 3.14) && (GREEKPI < 3.15), "GREEKPI is inaccurate!");

template<class T>struct Check { static_assert(sizeof(int) <= sizeof(T), "T is not big enough!");};

template<class Integral>Integral foo(Integral x, Integral y) { static_assert(std::is_integral<Integral>::value, "foo() parameter must be an integral type.");}

Page 27: C++ 11 Features

Uniform Initialization SyntaxC++std::string s("hello");

int m=int(); //default initialization

int arr[4]={0,1,2,3};struct tm today={0};

struct S { int x; int a[4]; S(): x(-1) { a[0] = 1; a[1] = 2; a[2] = 4; a[3] = 8; }};

C++11std::string s{"hello"};

int m{}; //default initialization

int arr[4]={0,1,2,3};struct tm today={0};

struct S { int x; int a[4]; S(): x{-1}, a{1, 2, 4, 8} {}};

Page 28: C++ 11 Features

Uniform Initialization SyntaxC++std::vector<int> vec;vec.push_back(1);vec.push_back(2);vec.push_back(3);

std::map<std::string, int> intMap;intMap["a"] = 1;intMap["b"] = 2;intMap["c"] = 3;

int* a = new int[3];a[0] = 1;a[1] = 2;a[2] = 0;

C++11std::vector<int> vec{1, 2, 3};

std::map<std::string, int> intMap{ {"a", 1}, {"b", 2}, {"c", 3} };

int* a = new int[3] { 1, 2, 0 };

Page 29: C++ 11 Features

ConstructorsC++class SomeType { int number; private: void Construct(int new_number) { number = new_number; }public: SomeType(int new_number) { Construct(new_number); } SomeType() { Construct(42); }};

// Note: Default argument not nice

C++11class SomeType { int number; public: SomeType(int new_number) : number(new_number) {} SomeType() : SomeType(42) {}};

Page 30: C++ 11 Features

ConstructorsC++class Foo {public: Foo() : abc(0), x(0), y(0), initialized(false) {}; Foo(int value) : abc(0), x(0), y(0), initialized(false) {}; private: int *abc; int x; int y; bool initialized;};

C++11class Foo {public: Foo() {}; Foo(int value) {}; private: int *abc = 0; int x = 0; int y = 0; bool initialized = false;};

Page 31: C++ 11 Features

ConstructorsC++class BaseClass {public: BaseClass() {}; BaseClass(int value) {};}; class DerivedClass : public BaseClass {public: DerivedClass() : BaseClass() {} DerivedClass(int value) : BaseClass(value) {}};

C++11class BaseClass {public: BaseClass() {}; BaseClass(int value) {};}; class DerivedClass : public BaseClass {public: using BaseClass::BaseClass;};

Page 32: C++ 11 Features

Default and DeleteC++struct NoCopy{private: NoCopy & operator =( const NoCopy & ) {}; NoCopy ( const NoCopy & ) {};};

struct A{ A() {} virtual ~A() {};};

C++11struct NoCopy{ NoCopy & operator =( const NoCopy & ) = delete; NoCopy ( const NoCopy & ) = delete;};

struct A{ A()=default; virtual ~A()=default;};

Page 33: C++ 11 Features

Tupletypedef std::tuple <int, double, long &, const char *> test_tuple;long lengthy = 12;test_tuple proof (18, 6.5, lengthy, "Ciao!"); lengthy = std::get<0>(proof); // Assign to 'lengthy' the value 18.std::get<3>(proof) = " Beautiful!"; // Modify the tuple’s fourth element.

Page 34: C++ 11 Features

Threadsstd::mutexstd::condition_variablestd::lock_guardstd::threadstd::async, std::future

Page 35: C++ 11 Features

A lot moremove semanticsregular expressionsnew algorithmsconstexprextern/alias templatesalternative function syntaxnew string literals...