88
cyberplus C++11 & C++14 Nagesh Rao Managing Director CyberPlus Infotech Pvt. Ltd. cyberplus ©2015, CyberPlus Infotech Pvt. Ltd.

C++11 & C++14

Embed Size (px)

Citation preview

Page 1: C++11 & C++14

cyberplus

C++11 & C++14Nagesh RaoManaging DirectorCyberPlus Infotech Pvt. Ltd.

cyberplus©2015, CyberPlus Infotech Pvt. Ltd.

Page 2: C++11 & C++14

cyberplus

C++11/14 Enhancements:

Data Types

Page 3: C++11 & C++14

cyberplus

Data Types

char (1)short (2)int (2,4)long (4,8)long long (8)

Page 4: C++11 & C++14

cyberplus

sizeof

class A { int x; B b;};

s = sizeof(A);s = sizeof(A::x);s = sizeof(A::b);

Page 5: C++11 & C++14

cyberplus

Memory Alignment

size_t alignof(T);

alignas(T)alignas(alignof(T))

alignas(float) float f;alignas(long) char buf[100*sizeof(long)];

Page 6: C++11 & C++14

cyberplus

C++11/14 Enhancements:

Literals

Page 7: C++11 & C++14

cyberplus

String Literals

C++03:

"Hello" const char[]L"Hello" const wchar_t[]

C++11:

u8"Hello \u20B9" const char[]u"Hello \u20B9" const char16_t[]U"Hello \U000020B9" const char32_t[]

Page 8: C++11 & C++14

cyberplus

Raw String Literals

R"delimiter(string)delimiter"

R"(Hello)"R"abc(Hello)abc"R"abc(Hello"Hello\Hello)Hello)abc"

u8R"abc(Hello"Hello\Hello)Hello)abc"uR"abc(Hello"Hello\Hello)Hello)abc"UR"abc(Hello"Hello\Hello)Hello)abc"

Page 9: C++11 & C++14

cyberplus

User Defined Literals

126_km55_m1600_LY2000_AD5_years12_mon

18.6_cm36.2_degC18.2_GB

"Hello"_lowercaseL"Hello"_lowercaseu8"Hello"_lowercaseu"Hello"_lowercaseU"Hello"_lowercase

C++14

0b100001010B10000101

24'000'0003.141'592'653'590b1000'010112'345'6'789'0

Raw form vs Cooked form

'1' '2' '3' '4' vs 1234

Page 10: C++11 & C++14

cyberplus

Integral User Defined Literals

Type operator "" _suffix(unsigned long long x);Type operator "" _suffix(const char *str, size_t len);Type operator "" _suffix<'c1','c2','c3'>();

Page 11: C++11 & C++14

cyberplus

Real User Defined Literals

Type operator "" _suffix(long double x);Type operator "" _suffix(const char *str, size_t len);Type operator "" _suffix<'c1','c2','c3'>();

Page 12: C++11 & C++14

cyberplus

String User Defined Literals

Type operator "" _suffix(const char *str, size_t len);Type operator "" _suffix(const wchar_t *str, size_t len);Type operator "" _suffix(const char16_t *str, size_t len);Type operator "" _suffix(const char32_t *str, size_t len);

Type operator "" _suffix(char c);Type operator "" _suffix(wchar_t c);Type operator "" _suffix(char16_t c);Type operator "" _suffix(char32_t c);

Page 13: C++11 & C++14

cyberplus

C++14 Standard Suffixes

Suffix Meaning

s A string literal

h Hours

min Minutes

s Seconds

ms Milliseconds

us Microseconds

ns Nanoseconds

Page 14: C++11 & C++14

cyberplus

Attributes

Device dev0;Device [[a1]] dev1 [[a2]];Device dev2 [[a3, a4]];Device dev3 [[a5(i,j)]];Device dev4 [[NS::a6]];[[a7]] while (!ready) { /* ... */ }

➢ Help convey information to compilers and tools➢ Replacement for #pragma➢ Usually present after named entities➢ Usually present before unnamed entitites

Page 15: C++11 & C++14

cyberplus

Attributes

C++14

[[deprecated]] void f();

[[deprecated("Use g() instead.")]] void f();

Page 16: C++11 & C++14

cyberplus

C++11/14 Enhancements:

Loops

Page 17: C++11 & C++14

cyberplus

Range Based Loops

for (int i=0; i<n; i++) { x[i]; }

for (int i: x) { i; }for (int &i: x) { i; }

for (vector<int>::iterator i=v.begin(); i!=v.end(); i++) { *i; }

for (int i: v) { i; }for (int &i: v) { i; }

Page 18: C++11 & C++14

cyberplus

C++11/14 Enhancements:

Constants

Page 19: C++11 & C++14

cyberplus

constexpr data members

constRuntime constants

const double PI=3.14;

const double PI_2=PI/2;

constexprCompile time constants

constexpr double PI=3.14;

constexpr double PI_2=PI/2;

Pre-processor Compiler Runtime

#define constexpr const

Page 20: C++11 & C++14

cyberplus

constexpr functions

Limitations in C++11:• Non-void return type

• No variable or data type definition

• Can contain non-executable statements and static_asserts

• Single executable statement: return

• Arguments (if any) are compile-time constants

• All constexpr functions are also treated as const member functions if non-static

int x[f()];constexpr int f() { return 100; }

Page 21: C++11 & C++14

cyberplus

constexpr in C++14

Enhancements:• Almost any statement permitted, including decisions and loops

• Not a non-static const member function automatically

– Can change only objects created within the constant context

• No goto statement

• No static or thread_local variables

• No local variables without initializers

Page 22: C++11 & C++14

cyberplus

Static Assertions

assertRuntime check

static_assertCompile time check

Pre-processor Compiler Runtime

#error static_assert assert

static_assert(condition, error_message);static_assert(MAX>100, "MAX is too big!");template <class T>class A { static_assert(sizeof(T)>32, "Size too big!"); }

Page 23: C++11 & C++14

cyberplus

C++11/14 Enhancements:Enumerations

Page 24: C++11 & C++14

cyberplus

Enumeration in C++03

Problems:1. Underlying type and size is platform dependent and non-portable

2. Enumerators expand into the scope of the enumeration

3. Easy conversion to integers makes undesirable possibilities possible

4. Forward declarations are not possible

Page 25: C++11 & C++14

cyberplus

Enumeration in C++11

enum class Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat};

Problem #1:Underlying type and size is platform dependent and non-portable

Solution:Underlying type is int (and can be changed by explicitly specifying), and is therefore portable

enum class Day : unsigned int { Sun, Mon, Tue, Wed, Thu, Fri, Sat };enum Day : unsigned int { Sun, Mon, Tue, Wed, Thu, Fri, Sat };

Page 26: C++11 & C++14

cyberplus

Enumeration in C++11

Problem #2:Enumerators expand into the scope of the enumeration

Solution:Enumerators are protected by the scope of the enumeration

enum class Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat };enum class SolarSystem { Sun, Earth, Moon };

Day d(Day::Tue);if (d == Day::Wed) { /* ... */ }

Page 27: C++11 & C++14

cyberplus

Enumeration in C++11

Problem #3:Easy conversion to integers makes undesirable possibilities possible

Solution:Enumerators are not implicitly convertible to other types

enum class Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat };enum class SolarSystem { Sun, Earth, Moon };

if (Day::Sun == SolarSystem::Sun) { /* ... */ }

Page 28: C++11 & C++14

cyberplus

Enumeration in C++11

Problem #4:Forward declarations are not possible

Solution:Forward declarations are possible as the underlying type is known

enum Day; // Wrong! Can't determine underlying type // without seeing enumeratorsenum class Day; // Ok, type is intenum class Day: char; // Ok, type is charenum Day: char; // Ok, type is char

Page 29: C++11 & C++14

cyberplus

C++11/14 Enhancements:

Typedef

Page 30: C++11 & C++14

cyberplus

C++11 Typedef

Better syntax:

typedef void (*fptr)(int);

using fptr = void (*)(int);

Works with templates too!

template <class T>using vec2D = vector<vector<T>>;

vec2D<int> x;vector<vector<int>> x;

Page 31: C++11 & C++14

cyberplus

C++11/14 Enhancements:

Pointers

Page 32: C++11 & C++14

cyberplus

NULL Pointers

NULL Pointer in C: (void*)0NULL Pointer in C++: 0

void print(char *str);void print(int x);

print(NULL);

NULL Pointer in C++11: nullptr

void print(char *str);void print(int x);

void print(nullptr_t ptr);

Page 33: C++11 & C++14

cyberplus

C++11/14 Enhancements:Smart Pointers

Page 34: C++11 & C++14

cyberplus

Smart Pointers: auto_ptr

void f(){ int *i = new int; // Don't forget to delete delete i;}

void f(){ int *i = new int; std::auto_ptr<int> p(i); //Don't have to delete}

A B

Page 35: C++11 & C++14

cyberplus

Smart Pointers: auto_ptr

int main(){ std::auto_ptr<int> p;

p = f(std::auto_ptr<int>(new int));}

std::auto_ptr<int> f(std::auto_ptr<int> p1){ std::auto_ptr<int> p2; p2 = p1; return p2;}

Page 36: C++11 & C++14

cyberplus

Smart Pointers: auto_ptr

*ptr

ptr->xptr.get()

ptr.release()

ptr.reset();

ptr.reset(ptr2);

Page 37: C++11 & C++14

cyberplus

Smart Pointers: auto_ptr

int *i = new int(3);std::auto_ptr<int> p1(i);std::cout << *p1 << endl; // 3std::cout << p1.get() << endl;// Address of the int

int *j;j=p1.get();std::cout << j << endl; // Address of the intstd::cout << p1 << endl; // Address of the int

Page 38: C++11 & C++14

cyberplus

Smart Pointers: auto_ptr

int *i = new int(3);std::auto_ptr<int> p1(i);std::cout << *p1 << endl; // 3std::cout << p1.get() << endl;// Address of the int

int *j;j=p1.release();std::cout << j << endl; // Address of the intstd::cout << p1 << endl; // NULL

delete j; //Deallocates memory

Page 39: C++11 & C++14

cyberplus

Smart Pointers: auto_ptr

int *i = new int(3);std::auto_ptr<int> p1(i);std::cout << *p1 << endl; // 3std::cout << p1.get() << endl;// Address of the int

p1.reset();std::cout << p1.get() << endl; // NULL

Page 40: C++11 & C++14

cyberplus

Smart Pointers: auto_ptr

int *i = new int(3);std::auto_ptr<int> p1(i);std::cout << *p1 << endl; // 3std::cout << p1.get() << endl;// Address of the int

p1.reset(new int(5));std::cout << p1.get() << endl; // Address of the new intstd::cout << *p1 << endl; // 5

Page 41: C++11 & C++14

cyberplus

Smart Pointers: auto_ptr

int *i = new int(3);std::auto_ptr<int> p1(i);std::cout << *p1 << endl; // 3std::cout << p1.get() << endl;// Address of the int

std::auto_ptr<int> p2;p2=p1; // Ownership transferred to p2std::cout << p1.get() << endl; // NULLstd::cout << p2.get() << endl; // Address of the int

Page 42: C++11 & C++14

cyberplus

Smart Pointers: unique_ptr

int *i = new int(3);std::unique_ptr<int> p1(i);std::cout << *p1 << endl; // 3std::cout << p1.get() << endl;// Address of the int

std::unique_ptr<int> p2;p2 = p1; // Error: Copy semantics not supportedp2 = std::move(p1); // Correct: Move semantics

std::cout << p1.get() << endl; // NULLstd::cout << p2.get() << endl; // Address of the int

Page 43: C++11 & C++14

cyberplus

Smart Pointers: shared_ptr

int *i = new int(3);std::shared_ptr<int> p1(i);std::cout << *p1 << endl; // 3std::cout << p1.get() << endl;// Address of the int

std::shared_ptr<int> p2;p2 = p1; // Both have ownership

std::cout << p1.get() << endl; // Address of the intstd::cout << p2.get() << endl; // Address of the int

p1.release(); // p2 still owns the raw pointerp2.release(); // Memory freed

Page 44: C++11 & C++14

cyberplus

Smart Pointers: weak_ptr

int *i = new int(3);std::shared_ptr<int> p1(i);std::cout << *p1 << endl; // 3std::cout << p1.get() << endl;// Address of the int

std::weak_ptr<int> wp1;wp1 = p1; // p1 retains ownership

std::cout << p1.get() << endl; // Address of the intstd::cout << wp1.get() << endl; // Address of the int

std::shared_ptr<int> p2 = wp1.lock();if (p2) { // p1 and p2 own the raw pointer}

Page 45: C++11 & C++14

cyberplus

Smart Pointers

std::shared_ptr<int> ptr(new int(5));std::shared_ptr<int> ptr = std::make_shared<int>(5);

C++14

std::unique_ptr<int> ptr(new int(5));std::unique_ptr<int> ptr = std::make_unique<int>(5);

Page 46: C++11 & C++14

cyberplus

C++11/14 Enhancements:

References

Page 47: C++11 & C++14

cyberplus

Rvalue References

3

f(Date(20,3,1946));

void f(Date d);void f(Date &d);void f(const Date &d) { d.day=1;}void f(Date &&d) { d.day=1;}

1

2

4

Temporaries:

d = Date(20,3,1946);

f(Date(20,3,1946));

d = f();Date f() {

return Date(20,3,1946);}

Use cases:1. Variables are treated as constants2. Constants are treated as variables

Page 48: C++11 & C++14

cyberplus

C++11/14 Enhancements:Type Inference

Page 49: C++11 & C++14

cyberplus

Type Inference

int x=10;auto y=10;

auto d = getCurrentDate();

int x[10];for (auto i: x) { i; }

for (auto i=v.begin(); i!=v.end(); i++)

for (auto i: v) { i; }for (auto &i: v) { i; }for (auto &&i: v) { i; }

Page 50: C++11 & C++14

cyberplus

Type Inference

auto a=10;auto b=a;decltype(a) c;decltype(a) d=a;decltype((a)) e=a;auto &f = a;auto &&h=a;decltype(10) g;

Page 51: C++11 & C++14

cyberplus

C++11/14 Enhancements:

Functions

Page 52: C++11 & C++14

cyberplus

Improved Function Syntax

class A {

int add(int x, int y);

};

int A::add(int x, int y) {

return x+y;

}

class A {

auto add(int x, int y) -> int;

};

auto A::add(int x, int y) -> int {

return x+y;

}

C++14 (Needs to be defined before use)

auto A::add(int x, int y) {

return x+y;

}

Page 53: C++11 & C++14

cyberplus

Improved Function Syntax

template <class A, class B>decltype(a+b) add(A &a, B &b) { return a+b; }

template <class A, class B>auto add(A &a, B &b) -> decltype(a+b){ return a+b; }

Page 54: C++11 & C++14

cyberplus

Lambda Expressions

Syntax:[capture] (parameters) -> return_type {function_body}

[](int x, int y) -> int { return x+y; }

int (*funcptr)(int,int);funcptr = [](int x, int y) -> int { return x+y; };std::cout << funcptr(2,3) << endl;

auto func = [](int x, int y) -> int { return x+y; };std::cout << func(2,3) << endl;

Page 55: C++11 & C++14

cyberplus

Lambda Expressions

To print all odd numbers from a vector:

std::vector<int> v = {1,6,7};

std::for_each(begin(v), end(v), [](int x){if (x%2==1) std::cout<<x<<endl; } );

Page 56: C++11 & C++14

cyberplus

Lambda Expressions

To print all odd numbers greater than 'n' from a vector:

std::vector<int> v = {1,6,7};int n=5;

std::for_each(begin(v), end(v), [n](int x){if (x%2==1 && x>n) std::cout<<x<<endl; } );

Page 57: C++11 & C++14

cyberplus

Lambda Expressions

To find the sum of all odd numbers in a vector:

std::vector<int> v = {1,6,7};int sum=0;

std::for_each(begin(v), end(v), [&sum](int x){if (x%2==1) sum+=x; } );

Page 58: C++11 & C++14

cyberplus

Lambda Expressions

To find the sum of all odd numbers and print all odd numbers greater than 'n':

std::vector<int> v = {1,6,7};int sum=0;int n=5;

std::for_each(begin(v), end(v), [n,&sum](int x){ if (x%2==1) { sum+=x; if (x>n) std::cout << x << endl; } } );std::cout << sum << endl;

Page 59: C++11 & C++14

cyberplus

Summary of Captures

Capture Meaning

[] No access to other variables

[a,b,c] Read-only access to specified variables only

[&a,&b] Read-write access to specified variables only

[a,&b,&c,d]

Read-only access to a and d; read-write access to b and c

[&] Read-write access to all variables

[=] Read-only access to all variables

[&,a,b,c] Read-write access to all variables; read-only access to specified variables

[=,&a,&b] Read-only access to all variables; read-write access to specified variables

Page 60: C++11 & C++14

cyberplus

Lambda Expressions

auto fptr = [](int x){ return 2*x; };

std::function<int(int)> fptr = [](int x){ return 2*x; };

int (*fptr)(int) = [](int x){ return 2*x; };

std::cout << fptr(2) << endl;

C++14

auto func = [](auto x, auto y) { return x+y; };

Page 61: C++11 & C++14

cyberplus

Defaulted/Deleted Functions

class A {public: A() = default; A(const A& a) = delete; A& operator = (const A& a) = delete;};

Page 62: C++11 & C++14

cyberplus

Defaulted/Deleted Functions

class A {public: void f(long x); void f(int x) = delete;};

class A {public: void f(long x); template <class T> void f(T x) = delete;};

Page 63: C++11 & C++14

cyberplus

Explicit Conversions

class Pointer {public: operator bool ();};

if (ptr) ...

void area(double side);area(ptr);

class Pointer {public: explicit operator bool ();};

if (ptr) ...

void area(double side);area(ptr);

Page 64: C++11 & C++14

cyberplus

C++11/14 Enhancements:Constructors

Page 65: C++11 & C++14

cyberplus

Move Constructors

Copy semantics:

A a1 = a2;

A::A(const A& a) { //...}

a1 = a2;

A& A::operator =(const A& a) { //...}

Move semantics:

A a1 = a2;

A::A(A&& a) { //...}

a1 = a2;

A& A::operator =(A&& a) { //...}

a1 = std::move(a2);

Page 66: C++11 & C++14

cyberplus

Constructor Delegation

class Counter{ int count;public: Counter() { setCount(0); }

Counter(int count) { setCount(count); }

void setCount(int count) { this.count = count; }};

class Counter{ int count;public: Counter(): Counter(0) { }

Counter(int count) { setCount(count); }

void setCount(int count) { this.count = count; }};

Page 67: C++11 & C++14

cyberplus

Data Member Initialization

class Counter{ int count=0;public: Counter() { }

Counter(int count) { this->count = count; }

};

Page 68: C++11 & C++14

cyberplus

Initializer Lists

struct Employee { int id; std::string name;};

Employee e1 = {20, “Ram”};

class Point { int x,y;};

Point p1 = {2,3};

Page 69: C++11 & C++14

cyberplus

Initializer Lists

class Point { int x,y; std::vector<int> values;public: Point(std::initializer_list<int> l): values(l) { x = values[0]; y = values[1]; }};

Point p1 = {2,3};

Page 70: C++11 & C++14

cyberplus

Initializer Lists

class Point { int x,y;public: Point(int x, int y) { this->x = x; this->y = y; // Anything else can go here }};

Point p1 = {2,3};

Page 71: C++11 & C++14

cyberplus

Initializer Lists

Point p = {2,3};Point p{2,3};

Point *p = new Point{2,3};

Point getPoint(int i) { return Point{x[i], y[i]};}

Point getPoint(int i) { return {x[i], y[i]};}

Point(int x, int y): x{x}, y{y} {}

Page 72: C++11 & C++14

cyberplus

Initializer Lists

class Point { int x,y; std::vector<int> values;public: void setPoint(std::initializer_list<int> l) { std::initializer_list<int>::iterator i; i = l.begin(); x = *i++; y = *i; }};

Point p;p.setPoint({2,3});

Page 73: C++11 & C++14

cyberplus

Initializer Lists

class Point { int x,y;public: Point getClosestPoint() { int x,y; //... return {x,y}; }};

Page 74: C++11 & C++14

cyberplus

C++11/14 Enhancements:

Inheritance

Page 75: C++11 & C++14

cyberplus

class A{public: virtual void f1() { } virtual void f2() { } virtual void f3() final { }};

class B: public A{public: void f1() { } // Ok: Overrides void f2(int x) { } // Ok: Does not override void f2(double x) override { } // Error, does not override void f3() { } // Error: cannot override};

Note: These apply only to virtual functions

override & final

Page 76: C++11 & C++14

cyberplus

final Classes

class A final{ //...};

class B: public A // Error: Cannot derive from final base class{ //...};

Page 77: C++11 & C++14

cyberplus

Base Class Constructors

class A { int x;public: A(int x): x{x} {}};

class B: public A {public: B(int x): A{x} {}};

class A { int x;public: A(int x): x{x} {}};

class B: public A {public: using A::A;};

Limitations:1. All constructors are inherited2. Derived class cannot have constructors with same signature as base class3. Multiple base classes cannot have constructors with the same signature

Page 78: C++11 & C++14

cyberplus

C++11/14 Enhancements:

Templates

Page 79: C++11 & C++14

cyberplus

C++03:std::vector<std::vector<int>> v;std::vector<std::vector<int> > v;

C++11:std::vector<std::vector<int>> v;

C++11:std::vector<std::vector<(3>1)>> v;

“>>” in Templates

Page 80: C++11 & C++14

cyberplus

Class declaration:class A;

Template class declaration:template class A<int>; // Instantiates

External template class declaration:extern template class A<int>; // Does not instantiate

extern Templates

Page 81: C++11 & C++14

cyberplus

Variadic Templates

template<class T1, class T2> void f(T1 x, T2 y);

template<class... T>void f(T... x);

template<class T1, class T2, class... T>void f(T1 x, T2 y, T... args);

Page 82: C++11 & C++14

cyberplus

Variadic Templates

template<class T>void f(T x){ //Action on x}

template<class T, class... Args>void f(T x, Args... args){ f(x); f(args...);}

sizeof...(Args)

Page 83: C++11 & C++14

cyberplus

Tuples

template<class... T> class std::tuple;

std::tuple<int, float> t1; // Default constructorstd::tuple(char, double> t2('a', 6.5);

t1=t2; //Same size; convertibleauto t3 = std::make_tuple(65, 8.3);

Page 84: C++11 & C++14

cyberplus

Tuples

std::tuple<int, float> t(10,6.5f);int x = std::get<0>(t);std::get<0>(t) = 20;

double y;std::tie(x, y) = t;std::tie(x, std::ignore) = t;auto t4 = std::make_tuple(std::ref(x), y);

C++14

std::tuple<int, float> t(10,6.5f);int x = std::get<int>(t1);

Page 85: C++11 & C++14

cyberplus

Tuples

typedef std::tuple<int, string> Employee;Employee e1(1,"Ram");Employee e2(2,"Shyam");

std::tuple_size<Employee>::valuestd::tuple_element<1,Employee>::type

Page 86: C++11 & C++14

cyberplus

Unordered Associative Containers

C++03 C++11 Addition

set unordered_set

multiset unordered_multiset

map unordered_map

multimap unordered_multimap

SORTING HASHING

C++14 allows heterogeneous lookup in associative containersThis requires “<” overload between the participating types, though

Page 87: C++11 & C++14

cyberplus

Variable Templates

C++14

template<class T> constexpr T pi = T(3.14);template<> constexpr const char *pi<const char*> = "Pi";

cout << toDegrees(pi<double>/2);cout << string(pi);

Page 88: C++11 & C++14

cyberplus

Thank you!

CyberPlus Infotech Pvt. Ltd.

32/5, 8th Main, 11th Cross, Malleswaram, Bangalore – 560 003.

Website: www.cyberplusit.comEmail: [email protected]

Blog: www.cyberplusindia.com/blogFacebook Fan Page: www.facebook.com/cyberplusindia