cyberplus
C++11 & C++14
Nagesh Rao
Managing Director
CyberPlus Infotech Pvt. Ltd.
cyberplus
©2015, CyberPlus Infotech Pvt. Ltd.
cyberplus
C++11/14
Enhancements:
Data Types
cyberplus
Data Types
char (1)
short (2)
int (2,4)
long (4,8)
long long (8)
cyberplus
sizeof
class A {
int x;
B b;
};
s = sizeof(A);
s = sizeof(A::x);
s = sizeof(A::b);
cyberplus
Memory Alignment
size_t alignof(T);
alignas(T)
alignas(alignof(T))
alignas(float) float f;
alignas(long) char buf[100*sizeof(long)];
cyberplus
C++11/14
Enhancements:
Literals
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[]
cyberplus
Raw String Literals
R"delimiter(string)delimiter"
R"(Hello)"
R"abc(Hello)abc"
R"abc(Hello"HelloHello)Hello)abc"
u8R"abc(Hello"HelloHello)Hello)abc"
uR"abc(Hello"HelloHello)Hello)abc"
UR"abc(Hello"HelloHello)Hello)abc"
cyberplus
User Defined Literals
126_km
55_m
1600_LY
2000_AD
5_years
12_mon
18.6_cm
36.2_degC
18.2_GB
"Hello"_lowercase
L"Hello"_lowercase
u8"Hello"_lowercase
u"Hello"_lowercase
U"Hello"_lowercase
C++14
0b10000101
0B10000101
24'000'000
3.141'592'653'59
0b1000'0101
12'345'6'789'0
Raw form vs Cooked form
'1' '2' '3' '4'
vs
1234
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'>();
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'>();
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);
cyberplus
C++14 Standard Suffixes
Suffix Meaning
s A string literal
h Hours
min Minutes
s Seconds
ms Milliseconds
us Microseconds
ns Nanoseconds
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
cyberplus
Attributes
C++14
[[deprecated]] void f();
[[deprecated("Use g() instead.")]] void f();
cyberplus
C++11/14
Enhancements:
Loops
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; }
cyberplus
C++11/14
Enhancements:
Constants
cyberplus
constexpr data members
const
Runtime constants
const double PI=3.14;
const double PI_2=PI/2;
constexpr
Compile time constants
constexpr double PI=3.14;
constexpr double PI_2=PI/2;
Pre-processor Compiler Runtime
#define constexpr const
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; }
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
cyberplus
Static Assertions
assert
Runtime check
static_assert
Compile 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!"); }
cyberplus
C++11/14
Enhancements:
Enumerations
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
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 };
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) { /* ... */ }
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) { /* ... */ }
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 enumerators
enum class Day; // Ok, type is int
enum class Day: char; // Ok, type is char
enum Day: char; // Ok, type is char
cyberplus
C++11/14
Enhancements:
Typedef
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;
cyberplus
C++11/14
Enhancements:
Pointers
cyberplus
NULL Pointers
NULL Pointer in C: (void*)0
NULL 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);
cyberplus
C++11/14
Enhancements:
Smart Pointers
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
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;
}
cyberplus
Smart Pointers: auto_ptr
*ptr
ptr->x
ptr.get()
ptr.release()
ptr.reset();
ptr.reset(ptr2);
cyberplus
Smart Pointers: auto_ptr
int *i = new int(3);
std::auto_ptr<int> p1(i);
std::cout << *p1 << endl; // 3
std::cout << p1.get() << endl;// Address of the int
int *j;
j=p1.get();
std::cout << j << endl; // Address of the int
std::cout << p1 << endl; // Address of the int
cyberplus
Smart Pointers: auto_ptr
int *i = new int(3);
std::auto_ptr<int> p1(i);
std::cout << *p1 << endl; // 3
std::cout << p1.get() << endl;// Address of the int
int *j;
j=p1.release();
std::cout << j << endl; // Address of the int
std::cout << p1 << endl; // NULL
delete j; //Deallocates memory
cyberplus
Smart Pointers: auto_ptr
int *i = new int(3);
std::auto_ptr<int> p1(i);
std::cout << *p1 << endl; // 3
std::cout << p1.get() << endl;// Address of the int
p1.reset();
std::cout << p1.get() << endl; // NULL
cyberplus
Smart Pointers: auto_ptr
int *i = new int(3);
std::auto_ptr<int> p1(i);
std::cout << *p1 << endl; // 3
std::cout << p1.get() << endl;// Address of the int
p1.reset(new int(5));
std::cout << p1.get() << endl; // Address of the new int
std::cout << *p1 << endl; // 5
cyberplus
Smart Pointers: auto_ptr
int *i = new int(3);
std::auto_ptr<int> p1(i);
std::cout << *p1 << endl; // 3
std::cout << p1.get() << endl;// Address of the int
std::auto_ptr<int> p2;
p2=p1; // Ownership transferred to p2
std::cout << p1.get() << endl; // NULL
std::cout << p2.get() << endl; // Address of the int
cyberplus
Smart Pointers: unique_ptr
int *i = new int(3);
std::unique_ptr<int> p1(i);
std::cout << *p1 << endl; // 3
std::cout << p1.get() << endl;// Address of the int
std::unique_ptr<int> p2;
p2 = p1; // Error: Copy semantics not supported
p2 = std::move(p1); // Correct: Move semantics
std::cout << p1.get() << endl; // NULL
std::cout << p2.get() << endl; // Address of the int
cyberplus
Smart Pointers: shared_ptr
int *i = new int(3);
std::shared_ptr<int> p1(i);
std::cout << *p1 << endl; // 3
std::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 int
std::cout << p2.get() << endl; // Address of the int
p1.release(); // p2 still owns the raw pointer
p2.release(); // Memory freed
cyberplus
Smart Pointers: weak_ptr
int *i = new int(3);
std::shared_ptr<int> p1(i);
std::cout << *p1 << endl; // 3
std::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 int
std::cout << wp1.get() << endl; // Address of the int
std::shared_ptr<int> p2 = wp1.lock();
if (p2) {
// p1 and p2 own the raw pointer
}
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);
cyberplus
C++11/14
Enhancements:
References
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 constants
2. Constants are treated as variables
cyberplus
C++11/14
Enhancements:
Type Inference
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; }
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;
cyberplus
C++11/14
Enhancements:
Functions
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;
}
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; }
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;
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; } );
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; } );
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; } );
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;
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
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; };
cyberplus
Defaulted/Deleted Functions
class A {
public:
A() = default;
A(const A& a) = delete;
A& operator = (const A& a) = delete;
};
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;
};
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);
cyberplus
C++11/14
Enhancements:
Constructors
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);
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;
}
};
cyberplus
Data Member Initialization
class Counter
{
int count=0;
public:
Counter() {
}
Counter(int count) {
this->count = count;
}
};
cyberplus
Initializer Lists
struct Employee {
int id;
std::string name;
};
Employee e1 = {20, “Ram”};
class Point {
int x,y;
};
Point p1 = {2,3};
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};
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};
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} {
}
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});
cyberplus
Initializer Lists
class Point {
int x,y;
public:
Point getClosestPoint() {
int x,y;
//...
return {x,y};
}
};
cyberplus
C++11/14
Enhancements:
Inheritance
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
cyberplus
final Classes
class A final
{
//...
};
class B: public A // Error: Cannot derive from final base class
{
//...
};
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 inherited
2. Derived class cannot have constructors with same signature as base class
3. Multiple base classes cannot have constructors with the same signature
cyberplus
C++11/14
Enhancements:
Templates
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
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
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);
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)
cyberplus
Tuples
template<class... T> class std::tuple;
std::tuple<int, float> t1; // Default constructor
std::tuple(char, double> t2('a', 6.5);
t1=t2; //Same size; convertible
auto t3 = std::make_tuple(65, 8.3);
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);
cyberplus
Tuples
typedef std::tuple<int, string> Employee;
Employee e1(1,"Ram");
Employee e2(2,"Shyam");
std::tuple_size<Employee>::value
std::tuple_element<1,Employee>::type
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 containers
This requires “<” overload between the participating types, though
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);
cyberplus
Thank you!
CyberPlus Infotech Pvt. Ltd.
32/5, 8th
Main, 11th
Cross,
Malleswaram, Bangalore – 560 003.
Website: www.cyberplusit.com
Email: info@cyberplusit.com
Blog: www.cyberplusindia.com/blog
Facebook Fan Page: www.facebook.com/cyberplusindia

C++11 & C++14