SlideShare a Scribd company logo
1 of 62
Restricted ยฉ 2017 Mentor Graphics Corporation
1
Core concepts of C++
Martin Ayvazyan
22/01/2019
Senior software/machine learning engineer
Restricted ยฉ 2017 Mentor Graphics Corporation
Contents
๏ฎ Memory management
๏ฎ Templates, Type deduction โ€“ decltype, auto
๏ฎ R-value references, Universal references, Move semantics, Perfect
Forwarding
๏ฎ Smart pointers, STL
๏ฎ Concurrency โ€“ multitasking, multithreading (not completed yet)
2
Restricted ยฉ 2017 Mentor Graphics Corporation
Memory management
๏ฎ Intel 4004 (1971) - 4 bit
๏ฎ Intel 8008 (1978) - 8 bit
๏ฎ Intel 8086 (1978) - 16 bit
๏ฎ Intel 80286 (1982) โ€“ 16 bit + protected mode
๏ฎ Intel 80386 (1985) โ€“ 32 bit + protected mode
3
Restricted ยฉ 2017 Mentor Graphics Corporation
Memory management
๏ฎ Memory addressing
โ€ข Real mode
โ€ข Linear addressing
โ€ข Segmentation
โ€ข Protected mode
โ€ข Segmentation
โ€ข Paging
4
Restricted ยฉ 2017 Mentor Graphics Corporation
Memory management
๏ฎ Memory addressing - real mode
All real mode memory addresses consist of a segment address
plus an offset address:
โ€ข the segment address (in one of the segment registers) defines
the beginning address of any 64Kb memory segment
โ€ข the offset address selects a location within the 64K byte
memory segment
ฯ’ = ฮฑ โˆ— 16 + ฮฒ where ฮฑฯต{๐‘๐‘ , ๐‘ ๐‘ , ๐‘‘๐‘ , ๐‘’๐‘ , ๐‘”๐‘ , ๐‘“๐‘ }
5
Restricted ยฉ 2017 Mentor Graphics Corporation
Memory management
๏ฎ Memory addressing โ€“ protected mode
โ€ข From logic address ๏ƒ  Linear address (32 bit)
โ€ข If paging is disabled ๏ƒ  Linear address ๏ƒง๏ƒจ Physical address
Assembly of segment register in protected mode:
6
15 3 2 1 0
PRLTIIndex
Selector
TI โ€“ table index, if TI==0 ๏ƒ  GDT, if TI==1 ๏ƒ LDT
PRL โ€“ request priority level (in case of CS CPL)
Restricted ยฉ 2017 Mentor Graphics Corporation
Memory management
๏ฎ Memory addressing โ€“ protected mode (TI=0)
7
GDTR
GDT
Descriptor
Index
byte5 byte4 byte3 byte2 byte1 byte0
Address Limit
Address+Index*8
Restricted ยฉ 2017 Mentor Graphics Corporation
Memory management
๏ฎ Memory addressing
โ€ข Protected mode
The protected mode processors use a look up table to compute
the physical address. Memory addressing is based on โ€˜Segment
Descriptorsโ€™ that define a memory-region and assign its
properties.
8
Type and
access-rights
Segment-
Base[23..16]
Word 3 Word 2
Segment-Base[15..0] Segment-Limit[15..0]
Word 1 Word 0
Segment-base
[31โ€ฆ24]
FLAGS(G, DB, โ€ฆ)
Restricted ยฉ 2017 Mentor Graphics Corporation
Memory management
๏ฎ Memory addressing - Protected mode
โ€ข Type and access-rights
9
P DPL S X C/D R/W A
P = Present (1=yes, 0=no)
DPL = Descriptor Privilege Level (00=supervisor, 11=user)
S = System-segment (0=yes, 1=no)
X = executable: 1=yes (i.e., code-segment), 0=no (i.e., data-segment)
C/D = Conforming code (1=yes, 0=no) when X-bit equals 1
expands-Down (1=yes, 0=no) when X-bit equals 0
R/W = Readable (1=yes, 0=no) when X-bit equals 1
Writable (1=yes, 0=no) when X-bit equals 0
A = segment has been Accessed by the CPU (1=yes, 0=no)
Restricted ยฉ 2017 Mentor Graphics Corporation
Memory management
๏ฎ Memory addressing - Protected mode
โ€ข Type and access-rights
10
S =1
S=0
I=0 E W
I=1 C R
TYPE(gates)
A
P โ€“ is the segment in memory
DPL โ€“ description privilege level
S โ€“ system descriptor(=1) or no(=0)
I โ€“ data segment(=0), code segment(=1)
E โ€“ common data segment(0)
W โ€“ is writable (if (E) assert(W==1);)
A โ€“ Access flag
C โ€“ conform(=1), non-*(=0) segment
R โ€“ Code segment can be read
DPLP
Restricted ยฉ 2017 Mentor Graphics Corporation
Memory management
๏ฎ Paging / Virtual memory management
11
CR3
PD
PDE
PT
PTE
ฮฑ ฮฒ ฯ’
linear address
Page
Restricted ยฉ 2017 Mentor Graphics Corporation
Memory management
๏ฎ Computer memory hierarchy
12
Registers
Processor cache(L1, L2, โ€ฆ)
RAM
Hard drives
1 ns.
2 ns.
10 ns.
10 ms.
< 1Kb
4 Mb
512-2048 Mb
200-1000Gb
Restricted ยฉ 2017 Mentor Graphics Corporation
Memory management
๏ฎ C++ memory storages (in general)
โ€” Static
โ€” Heap
โ€” Stack
13
Restricted ยฉ 2017 Mentor Graphics Corporation
Memory management
๏ฎ C++ memory storages โ€“ static memory storage
Possible problems of static objects initialization:
โ€” static initialization order โ€˜fiascoโ€™ problem โ€“ here we have a 50%-50%
chance of corrupting the program(if y would be constructed before x).
14
// f1.cpp
#include โ€œT1.hโ€
T1 obj1;
// f2.cpp
#include โ€œT2.hโ€
T2 obj2;
// T2.cpp
#include โ€œT2.hโ€
T2::T2{
x.do_dmth();
}
Restricted ยฉ 2017 Mentor Graphics Corporation
Memory management
๏ฎ C++ memory storages โ€“ static memory storage
Solution for the problem - Construct On First Use Idiom - i.e. replace
the namespace-scope/global T1 object with a namespace-
scope/global function f_obj() that returns the Fred object by
reference:
15
// f1.cpp
T1& get()
{
static T1* ptr = new T1();
return *ptr;
}
// f1.cpp
T1& get()
{
static T1 ref;
return ref;
}
?
need to be 100% sure our static object:
(a) gets constructed prior to its first use
(b) doesnโ€™t get destructed until after its last use.
Restricted ยฉ 2017 Mentor Graphics Corporation
Memory management
๏ฎ C++ memory storages โ€“ heap memory storage
โ€” new operator to allocate an object in memory
โ€” delete operator to deallocate an allocated object
Try to avoid heap memory fragmentations as much as possible.
Use placement new if you have enough knowledge about it:
16
void fn()
{
char memory[sizeof(T)];
void* p = memory;
T* f = new(p) T();
// do smth.
}
Restricted ยฉ 2017 Mentor Graphics Corporation
Memory management
๏ฎ C++ memory storages โ€“ heap memory storage / placement new
17
void fn()
{
char memory[sizeof(T)];
void* p = memory;
T* f = new(p) T();
// do smth.
}
void fn()
{
char memory[sizeof(T)];
void* p = memory;
T* f = new(p) T();
// do smth.
f->~T();
}
Restricted ยฉ 2017 Mentor Graphics Corporation
Memory management
๏ฎ C++ memory storages โ€“ โ€˜stackโ€™ memory storage
โ€” Stack variables are local in nature.
โ€” There is a limit (varies with OS) on the size of variables that can be stored
on the stack.
โ€” The stack grows and shrinks as functions push and pop local variables
โ€” There is no need to manage the memory yourself, variables are allocated
and freed automatically
โ€” Stack variables only exist while the function that created them, is running
18
Restricted ยฉ 2017 Mentor Graphics Corporation
Memory management
๏ฎ C++ memory storages โ€“ stack vs heap
19
Stack Heap
very fast access (relatively) slower access
don't have to explicitly de-allocate variables no guaranteed efficient use of space
limit on stack size (OS-dependent) no limit on memory size
local variables only variables can be accessed globally
space is managed efficiently by CPU,
memory will not become fragmented
allocated memory must be managed
variables cannot be resized variables can be resized
using realloc()
Restricted ยฉ 2017 Mentor Graphics Corporation
Memory management
๏ฎ Structure Padding
โ€ข Architecture of a computer processor is such a way that it can read 1 word
(4 byte in 32 bit processor) from memory at a time.
โ€ข To make use of this advantage of processor, data are always aligned as 4
bytes package which leads to insert empty addresses between other
memberโ€™s address.
โ€ข Because of this size of the structure is always not same as what we think.
โ€ข In order to align the data in memory, one or more empty bytes are
inserted between memory addresses which are allocated for other
structure members while memory allocation.
20
Restricted ยฉ 2017 Mentor Graphics Corporation
Memory management
๏ฎ Structure Padding
21
struct A {};
struct B
{bool b};
struct C
{bool b; int x;};
struct C
{bool b1, b2; int x;};
struct C
{bool b1; int x; bool b2};
[](){};
[x=true, y=2, z= true](){};
[x=true, y=2, z= true](){};
std::tuple<bool, int>
std::tuple<bool, bool,
int>
std::tuple<bool,int,
bool>
std::function<void()>
Restricted ยฉ 2017 Mentor Graphics Corporation
Memory management
๏ฎ False sharing
22
class T
{ int x1, x2;};
static T obj;
int f()
{
int sum=0;
for (i=0;i<131313; ++i) sum +=obj.x1;
return sum;
}
void g()
{
for (i=0;i<131313; ++i) ++obj.x2;
}
When f and g are running concurrently
sum may need re-read x1 from main
memory event though concurrent
modification of x2 does not affect on
x1.
Restricted ยฉ 2017 Mentor Graphics Corporation
Memory management
๏ฎ False sharing
23
Restricted ยฉ 2017 Mentor Graphics Corporation
Memory management
๏ฎ Value categories in C++
Each C++ expression is characterized by two independent properties: a type
and a value. Each expression has some non-reference type and each
expression belongs to a value category.
โ€ข C++98
An expression is either an:
โ€ข lvalue โ€“ occupies some identifiable location in memory
โ€ข rvalue โ€“ !lvalue
โ€ข C++11
โ€ข lvalue
โ€ข rvalue
โ€ข xvalue
โ€ข prvalue
โ€ข glvalue
24
Restricted ยฉ 2017 Mentor Graphics Corporation
Memory management
๏ฎ Value categories in C++11
Two properties of expressions
โ€ข Can be moved from
Move constructor, move โ€˜=โ€˜operator, or another function overload that implements move
semantics can bind to the expression.
โ€ข Has identity
Itโ€™s possible to determine whether the expression refers to the same entity as another
expression, such as by comparing addresses of the objects or the functions they
identify(obtained directly or indirectly).
25
Restricted ยฉ 2017 Mentor Graphics Corporation
Memory management
๏ฎ Value categories in C++11
โ€ข glvalue - has identity. Is either lvalue or xvalue.
โ€ข rvalue โ€“ can be moved from. Is either prvalue or xvalue.
โ€ข lvalue โ€“ has identity and canโ€™t be moved from. { the name of a variable, a
function, function call whose return type is lvalue(++i), assignment and
compound assignment, built-in comma expression where the second
operand is lvalue, a ? b : c(lvalues), string literal, static_cast<T&> }
โ€ข xvalue โ€“ has identity and can be moved from. { std::move,
static_cast<T&&>, the member of object like a.m(where a is an rvalue and
m is non-static data member of non-reference type) }
โ€ข prvalue- does not identity and canโ€™t be moved from. {literal, i++, expr.
Whose return type non-ref, built-in address-of expression, static_cast<int>
}
26
Restricted ยฉ 2017 Mentor Graphics Corporation
Memory management
๏ฎ Value categories
27
expression
rvalue glvalue
prvalue xvalue lvalue
Restricted ยฉ 2017 Mentor Graphics Corporation
Memory management
๏ฎ Bitfields
28
struct S {
bool b1: 1,
bool b2: 1,
โ€ฆ
bool b8: 1
};
union {
struct S {
bool b1: 1,
bool b2: 1,
โ€ฆ
bool b8: 1
};
bool dummy;
};
Restricted ยฉ 2017 Mentor Graphics Corporation
Memory management
๏ฎ Things need to attention
โ€” const_cast
โ€” (a+b)-c != a+(b-c)
โ€” stack and realloc
โ€” using compile-time unknown expression to define size of stakโ€™s objects
โ€” taking address of a bitfield
โ€” size of an array like arr[N] known at compile time! (T(&)[N])
29
Restricted ยฉ 2017 Mentor Graphics Corporation
Templates / Type deduction โ€“ auto and decltype
๏ฎ Type deduction for templates
MyT x;
const MyT& y = x;
๐‘ก๐‘’๐‘š๐‘๐‘™๐‘Ž๐‘ก๐‘’ < ๐‘๐‘™๐‘Ž๐‘ ๐‘  ๐‘‡ > ๐‘ฃ๐‘œ๐‘–๐‘‘ ๐‘“ ๐‘‡2 ๐‘Ž๐‘Ÿ๐‘” โ€ฆ
โ€” ๐‘ก๐‘’๐‘š๐‘๐‘™๐‘Ž๐‘ก๐‘’ < ๐‘๐‘™๐‘Ž๐‘ ๐‘  ๐‘‡ > ๐‘ฃ๐‘œ๐‘–๐‘‘ ๐‘“ ๐‘‡ ๐‘Ž๐‘Ÿ๐‘” โ€ฆ ๏ƒ  f(x), f(y) T2, T2 ?
โ€” ๐‘ก๐‘’๐‘š๐‘๐‘™๐‘Ž๐‘ก๐‘’ < ๐‘๐‘™๐‘Ž๐‘ ๐‘  ๐‘‡ > ๐‘ฃ๐‘œ๐‘–๐‘‘ ๐‘“ ๐‘‡& ๐‘Ž๐‘Ÿ๐‘” โ€ฆ ๏ƒ  f(x), f(y) T2, T2 ?
โ€” ๐‘ก๐‘’๐‘š๐‘๐‘™๐‘Ž๐‘ก๐‘’ < ๐‘๐‘™๐‘Ž๐‘ ๐‘  ๐‘‡ > ๐‘ฃ๐‘œ๐‘–๐‘‘ ๐‘“ ๐‘๐‘œ๐‘›๐‘ ๐‘ก ๐‘‡& ๐‘Ž๐‘Ÿ๐‘” โ€ฆ ๏ƒ  f(x), f(y) T2, T2 ?
โ€” ๐‘ก๐‘’๐‘š๐‘๐‘™๐‘Ž๐‘ก๐‘’ < ๐‘๐‘™๐‘Ž๐‘ ๐‘  ๐‘‡ > ๐‘ฃ๐‘œ๐‘–๐‘‘ ๐‘“ ๐‘‡&& ๐‘Ž๐‘Ÿ๐‘” โ€ฆ ๏ƒ  f(x), f(y) T2, T2 ?
โ€” ๐‘ก๐‘’๐‘š๐‘๐‘™๐‘Ž๐‘ก๐‘’ < ๐‘๐‘™๐‘Ž๐‘ ๐‘  ๐‘‡ > ๐‘ฃ๐‘œ๐‘–๐‘‘ ๐‘“ ๐‘‡ ๐‘Ž๐‘Ÿ๐‘” โ€ฆ ๏ƒ  f(&x), f(&y) T2, T2 ?
30
Restricted ยฉ 2017 Mentor Graphics Corporation
Templates / Type deduction โ€“ auto and decltype
๏ฎ Type deduction for templates
MyT x;
const MyT& y = x;
๐‘ก๐‘’๐‘š๐‘๐‘™๐‘Ž๐‘ก๐‘’ < ๐‘๐‘™๐‘Ž๐‘ ๐‘  ๐‘‡ > ๐‘ฃ๐‘œ๐‘–๐‘‘ ๐‘“ ๐‘‡2 ๐‘Ž๐‘Ÿ๐‘” โ€ฆ
โ€” ๐‘ก๐‘’๐‘š๐‘๐‘™๐‘Ž๐‘ก๐‘’ < ๐‘๐‘™๐‘Ž๐‘ ๐‘  ๐‘‡ > ๐‘ฃ๐‘œ๐‘–๐‘‘ ๐‘“ ๐‘‡ ๐‘Ž๐‘Ÿ๐‘” โ€ฆ ๏ƒ  f(x), f(y) T2=MyT, T2=MyT
โ€” ๐‘ก๐‘’๐‘š๐‘๐‘™๐‘Ž๐‘ก๐‘’ < ๐‘๐‘™๐‘Ž๐‘ ๐‘  ๐‘‡ > ๐‘ฃ๐‘œ๐‘–๐‘‘ ๐‘“ ๐‘‡& ๐‘Ž๐‘Ÿ๐‘” โ€ฆ ๏ƒ  f(x), f(y) T2=MyT, T2=const MyT
โ€” ๐‘ก๐‘’๐‘š๐‘๐‘™๐‘Ž๐‘ก๐‘’ < ๐‘๐‘™๐‘Ž๐‘ ๐‘  ๐‘‡ > ๐‘ฃ๐‘œ๐‘–๐‘‘ ๐‘“ ๐‘๐‘œ๐‘›๐‘ ๐‘ก ๐‘‡& ๐‘Ž๐‘Ÿ๐‘” โ€ฆ ๏ƒ  f(x), f(y) T2=MyT, T2=MyT
โ€” ๐‘ก๐‘’๐‘š๐‘๐‘™๐‘Ž๐‘ก๐‘’ < ๐‘๐‘™๐‘Ž๐‘ ๐‘  ๐‘‡ > ๐‘ฃ๐‘œ๐‘–๐‘‘ ๐‘“ ๐‘‡&& ๐‘Ž๐‘Ÿ๐‘” โ€ฆ ๏ƒ  f(x) T2=MyT&, T2=const MyT&
โ€” ๐‘ก๐‘’๐‘š๐‘๐‘™๐‘Ž๐‘ก๐‘’ < ๐‘๐‘™๐‘Ž๐‘ ๐‘  ๐‘‡ > ๐‘ฃ๐‘œ๐‘–๐‘‘ ๐‘“ ๐‘‡ ๐‘Ž๐‘Ÿ๐‘” โ€ฆ ๏ƒ  f(&x), f(&y) T2=MyT*, T2=const MyT*
31
Restricted ยฉ 2017 Mentor Graphics Corporation
Templates / Type deduction โ€“ auto and decltype
๏ฎ Type deduction for templates
template <class T>
void f(const T& arg)
{ T par = arg; par.non_const_fn(); }
template <class T>
void f(T& arg)
{ T par = arg; par.non_const_fn(); }
template <class T>
void f(T arg)
{ T par = arg; par.non_const_fn(); }
32
Restricted ยฉ 2017 Mentor Graphics Corporation
Templates / Type deduction โ€“ auto and decltype
๏ฎ auto
33
struct S
{
S(int x) :m(x){}
int m;
};
S operatorโ€โ€_ma13
(unsigned long long x)
{
return S(static_cast<int>(x));
}
auto x1 = 13_ma13;
auto x2(13_ma13);
auto x3 = {13_ma13};
auto x4 {13_ma13};
auto x5 = {13_ma13, 13_ma13};
auto x6 {13_ma13, 13_ma13};
auto x7 ={13_ma13, 13};
template <class T>
void f(T);
f({13_ma13});
f({13_ma13, 13_ma13});
?
?
?
?
?
?
?
?
?
Restricted ยฉ 2017 Mentor Graphics Corporation
Templates / Type deduction โ€“ auto and decltype
๏ฎ auto
34
auto x1 = 13_ma13;
auto x2(13_ma13);
auto x3 = {13_ma13};
auto x4 {13_ma13};
auto x5 = {13_ma13, 13_ma13};
auto x6 {13_ma13, 13_ma13};
auto x7 ={13_ma13, 13};
template <class T>
void f(T);
f(13_ma13);
f({13_ma13});
f({13_ma13, 13_ma13});
S
S
std::initializer_list<S>
S
std::initializer_list<S>
error โ€ฆ. (add โ€˜=โ€˜ before the {)
std::initializer_list<S>
S
error โ€“ cannot deduce T
error โ€“ cannot deduce T
Restricted ยฉ 2017 Mentor Graphics Corporation
Templates / Type deduction โ€“ auto and decltype
๏ฎ auto
35
auto f()
{ return 13_ma13;}
auto fn1 = [] (auto s) {โ€ฆ}
auto fn2 = [] (const auto& s)
{โ€ฆ}
f1(13_ma13);
f1({13_ma13});
f2({13_ma13});
?
cannot
?
Restricted ยฉ 2017 Mentor Graphics Corporation
Templates / Type deduction โ€“ auto and decltype
๏ฎ auto
36
auto f()
{ return 13_ma13;}
auto fn1 = [] (auto s) {โ€ฆ}
auto fn2 = [] (const auto& s)
{โ€ฆ}
f1(13_ma13);
f1({13_ma13});
f2({13_ma13});
S
a braced-enclosed list does not provide return value
a braced-enclosed list does not provide return value
Restricted ยฉ 2017 Mentor Graphics Corporation
Templates / Type deduction โ€“ auto and decltype
๏ฎ auto
โ€ข In general itโ€™s the same as template type deduction. The main
difference is that auto assumes that a braced initializers
represents a std::initializer_list, but TTD-doesnโ€™t.
โ€ข Auto in function return type or a lambda parameter implies TTD,
not auto type deduction.
37
Restricted ยฉ 2017 Mentor Graphics Corporation
Templates / Type deduction โ€“ auto and decltype
๏ฎ auto and decltype
38
int x[10];
auto f1(int i)
{ return x[i];}
decltype(auto) f2(int i)
{ return x[i];}
f1(0) = 4;
f2(0) = 4
Restricted ยฉ 2017 Mentor Graphics Corporation
Templates / Type deduction โ€“ auto and decltype
๏ฎ decltype
โ€ข Decltype almost always yields the type of expression without modification.
โ€ข For lvaluesโ€™ of type T decltype always reports a T&
39
Restricted ยฉ 2017 Mentor Graphics Corporation
Templates / Type deduction โ€“ auto and decltype
๏ฎ decltype
40
decltype(auto) f()
{
bool b;
โ€ฆ
return (b);
}
UNDEFINED BEHAVIOR!!!!!
Restricted ยฉ 2017 Mentor Graphics Corporation
Templates / Type deduction โ€“ auto and decltype
๏ฎ partial specialization
๏ฎ static_assert
41
template <class T>
void g(T) {cout<<โ€œAโ€;}
template <>
void g<int>(int){cout<<โ€œBโ€;}
template <class T>
void f(T) { static_assert(std::is_same_v<T, int>); }
g(1); // B
g(1.); // A
f(1); // fine
f(1.); //compile error
Restricted ยฉ 2017 Mentor Graphics Corporation
Templates / Type deduction โ€“ auto and decltype
๏ฎ std::enable_if
42
template<class T, typename = void>
class A{};
template<class T>
class A<T, typename =
std::enable_if_t<std::is_fundamental_v<T>>
{};
template<class T, typename = void>
class A{};
template<class T>
class A<T, typename =
std::enable_if_t<std::is_fundamental_v<T>>
{};
template<class T>
class A<T, typename =
std::enable_if_t<std::is_integral_v<T>>
{};
Restricted ยฉ 2017 Mentor Graphics Corporation
Templates / Type deduction โ€“ auto and decltype
class D
{virtual void f(){}};
template<class T>
class D
{
virtual void f(){};
};
template<class T>
class D
{
template <class T2=T>
virtual void f(){};
};
43
?
?
?
Restricted ยฉ 2017 Mentor Graphics Corporation
Templates / Type deduction โ€“ auto and decltype
class D
{virtual void f(){}};
template<class T>
class D
{
virtual void f(){};
};
template<class T>
class D
{
template <class T2=T>
virtual void f(){};
};
44
OK
OK
Error โ€“ virtual is not allowed
in a function template
declaration
Restricted ยฉ 2017 Mentor Graphics Corporation
R-value references, Universal references, Move
semantics, Perfect Forwarding
๏ฎ R-value references - &&
๏ฎ Universal references - &&
๏ฎ Move semantics - via std::move
๏ฎ Perfect forwarding โ€“ via std::forward
45
Restricted ยฉ 2017 Mentor Graphics Corporation
R-value references, Universal references, Move
semantics, Perfect Forwarding
๏ฎ R-value references
46
void f(S&& obj)
{/โ€ฆ/}
f(13_ma13);
S x = 13_ma13;
f(x);
fine
an rvalue ref. cant be bound to an lvalue
Restricted ยฉ 2017 Mentor Graphics Corporation
R-value references, Universal references, Move
semantics, Perfect Forwarding
๏ฎ R-value references
47
struct S
{
void f1() & {}
void f2() && {}
};
auto x = 13_ma13;
x.f1();
x.f2();
fine
error- function canโ€™t be called on lvalue
Restricted ยฉ 2017 Mentor Graphics Corporation
R-value references, Universal references, Move
semantics, Perfect Forwarding
๏ฎ Universal referances
48
template <class T>
void f(T&&)
{โ€ฆ}
auto&& s = 13_ma13;
If a function template parameter has type T&& for a deduced
type, or an object is declared using auto&&, the paramet or
object is a UR.
UR correspond to rvalue if they are initialized with rvalues. The
same for lvalue.
Restricted ยฉ 2017 Mentor Graphics Corporation
R-value references, Universal references, Move
semantics, Perfect Forwarding
๏ฎ Move semantics
49
std::vector<int> x{1,2,3,4};
std::vector<int> y=std::move(x);
assert(x.empty());
assert(y.size() == 4);
//possible impl.
template<typename T>
constexpr typename
std::remove_reference<T>::type&&
move(T&& t) noexcept
{
return static_cast<typename
std::remove_reference<T>::type&&>(t);
}
Restricted ยฉ 2017 Mentor Graphics Corporation
R-value references, Universal references, Move
semantics, Perfect Forwarding
๏ฎ Perfect Forwarding
50
template <class T>
void f1(T&& val)
{
f(val);
}
template <class T>
void f2(T&& val)
{
f(std::forward<T>(val));
}
S s = 13_ma13;
f1(s); //in f is passed ?
f1(13_ma13); // in f is passed ?
f2(s); // in f is passed ?
f2(13_ma13); // in f is passed ?
Restricted ยฉ 2017 Mentor Graphics Corporation
R-value references, Universal references, Move
semantics, Perfect Forwarding
๏ฎ Perfect Forwarding
51
void f(S&) {cout<<โ€œlvalueโ€;}
void f(S&&) {cout<<โ€œrvalueโ€;}
template <class T>
void f1(T&& val)
{
f(val);
}
template <class T>
void f2(T&& val)
{
f(std::forward<T>(val));
}
S s = 13_ma13;
f1(s); //lvalue
f1(13_ma13); // lvalue
f2(s); // lvalue
f2(13_ma13); // rvalue
Restricted ยฉ 2017 Mentor Graphics Corporation
R-value references, Universal references, Move
semantics, Perfect Forwarding
๏ฎ Use std::move on rvalue referances, std::forward on universal
referances.
๏ฎ Never use std::move or std::forward to local objects it they would
otherwise be eligible for the RVO.
52
Restricted ยฉ 2017 Mentor Graphics Corporation
R-value references, Universal references, Move
semantics, Perfect Forwarding
๏ฎ Variadic templates
53
template<typename โ€ฆ Args>
void f(Args&& โ€ฆargs)
{
f1(std::forward<Args>(args)โ€ฆ);
}
template<typename โ€ฆ Args>
class A
{
public:
void f(Args&&โ€ฆ args)
{
f1(std::forward<Args>(args)โ€ฆ);
}
};
Restricted ยฉ 2017 Mentor Graphics Corporation
R-value references, Universal references, Move
semantics, Perfect Forwarding
template <class T>
struct A
{
void f(T&& obj)
{}
template <class T2 = T>
void f2(T2&& obj)
{}
};
54
A<S> obj;
S obj = 13_ma13;
obj.f(13_ma13);
obj.f(s);
obj.f2(13_ma13);
obj.f2(s);
?
?
?
?
Restricted ยฉ 2017 Mentor Graphics Corporation
R-value references, Universal references, Move
semantics, Perfect Forwarding
template <class T>
struct A
{
void f(T&& obj)
{}
template <class T2 = T>
void f2(T2&& obj)
{}
};
55
A<S> obj;
S obj = 13_ma13;
obj.f(13_ma13);
obj.f(s);
obj.f2(13_ma13);
obj.f2(s);
OK
error
OK
OK
Restricted ยฉ 2017 Mentor Graphics Corporation
Smart pointers, STL
๏ฎ Smart pointers
โ€ข unique_ptr
โ€ข shared_ptr
โ€ข weak_ptr
56
Restricted ยฉ 2017 Mentor Graphics Corporation
Smart pointers, STL
๏ฎ Smart pointers โ€“ unique_ptr
โ€ข Movable, non-copyable
57
template <typename T, typename D>
class unique_ptr;
template<typename T, typename D>
class unique_ptr<T[], D>;
template <typename T, typeneme โ€ฆ Args>
unique_ptr make_unique(Args&&โ€ฆ args);
Restricted ยฉ 2017 Mentor Graphics Corporation
Smart pointers, STL
๏ฎ Smart pointers โ€“ shared_ptr
โ€ข Movable, copyable
58
template <typename T>
class shared_ptr;
template<class T, typename โ€ฆ Args>
shared_ptr<T> make_shared(Args&& โ€ฆ args);
Restricted ยฉ 2017 Mentor Graphics Corporation
Smart pointers, STL
๏ฎ Smart pointers โ€“ weak_ptr
โ€ข Movable, copyable
59
template<class T>
class weak_ptr
{
โ€ฆ
shared_ptr<T> lock();
โ€ฆ
};
Restricted ยฉ 2017 Mentor Graphics Corporation
Smart pointers, STL
๏ฎ STL
โ€ข std::array
โ€ข std::unordered_set/map
โ€ข std::unordered_multiset/multimap
โ€ข std::emplace for all containers
โ€ข Parallel execution support for STL algorithms
60
Restricted ยฉ 2017 Mentor Graphics Corporation
Concurrency โ€“ multitasking, multithreading
๏ฎ multi-threading
๏ฎ multi-tasking
๏ฎ std::mutex
๏ฎ std::condition_variable
๏ฎ std::atomic
๏ฎ std::thread
๏ฎ std::future
๏ฎ std::async
61
Restricted ยฉ 2017 Mentor Graphics Corporation
62
Thank you!

More Related Content

What's hot

Financial Networks IV. Analyzing and Visualizing Exposures
Financial Networks IV. Analyzing and Visualizing ExposuresFinancial Networks IV. Analyzing and Visualizing Exposures
Financial Networks IV. Analyzing and Visualizing ExposuresKimmo Soramaki
ย 
Ijmsr 2016-05
Ijmsr 2016-05Ijmsr 2016-05
Ijmsr 2016-05ijmsr
ย 
HDR Defence - Software Abstractions for Parallel Architectures
HDR Defence - Software Abstractions for Parallel ArchitecturesHDR Defence - Software Abstractions for Parallel Architectures
HDR Defence - Software Abstractions for Parallel ArchitecturesJoel Falcou
ย 
Opengl lec 3
Opengl lec 3Opengl lec 3
Opengl lec 3elnaqah
ย 
Hpg2011 papers kazakov
Hpg2011 papers kazakovHpg2011 papers kazakov
Hpg2011 papers kazakovmistercteam
ย 
Neural Networks - How do they work?
Neural Networks - How do they work?Neural Networks - How do they work?
Neural Networks - How do they work?Accubits Technologies
ย 
Gate-Cs 1995
Gate-Cs 1995Gate-Cs 1995
Gate-Cs 1995Ravi Rajput
ย 
Data structure-question-bank
Data structure-question-bankData structure-question-bank
Data structure-question-bankJagan Mohan Bishoyi
ย 
Penn graphics
Penn graphicsPenn graphics
Penn graphicsfloored
ย 
Practical C++ Generative Programming
Practical C++ Generative ProgrammingPractical C++ Generative Programming
Practical C++ Generative ProgrammingSchalk Cronjรฉ
ย 
Class[2][29th may] [javascript]
Class[2][29th may] [javascript]Class[2][29th may] [javascript]
Class[2][29th may] [javascript]Saajid Akram
ย 
Resource to Performance Tradeoff Adjustment for Fine-Grained Architectures โ”€A...
Resource to Performance Tradeoff Adjustment for Fine-Grained Architectures โ”€A...Resource to Performance Tradeoff Adjustment for Fine-Grained Architectures โ”€A...
Resource to Performance Tradeoff Adjustment for Fine-Grained Architectures โ”€A...Fahad Cheema
ย 
RNN, LSTM and Seq-2-Seq Models
RNN, LSTM and Seq-2-Seq ModelsRNN, LSTM and Seq-2-Seq Models
RNN, LSTM and Seq-2-Seq ModelsEmory NLP
ย 
MATHEON D-Day: Numerical simulation of integrated circuits for future chip ge...
MATHEON D-Day: Numerical simulation of integrated circuits for future chip ge...MATHEON D-Day: Numerical simulation of integrated circuits for future chip ge...
MATHEON D-Day: Numerical simulation of integrated circuits for future chip ge...Dagmar Monett
ย 
Asymptotic Notation and Data Structures
Asymptotic Notation and Data StructuresAsymptotic Notation and Data Structures
Asymptotic Notation and Data StructuresAmrinder Arora
ย 
Predicting organic reaction outcomes with weisfeiler lehman network
Predicting organic reaction outcomes with weisfeiler lehman networkPredicting organic reaction outcomes with weisfeiler lehman network
Predicting organic reaction outcomes with weisfeiler lehman networkKazuki Fujikawa
ย 
Review_Cibe Sridharan
Review_Cibe SridharanReview_Cibe Sridharan
Review_Cibe SridharanCibe Sridharan
ย 
Auto encoding-variational-bayes
Auto encoding-variational-bayesAuto encoding-variational-bayes
Auto encoding-variational-bayesmehdi Cherti
ย 

What's hot (20)

Financial Networks IV. Analyzing and Visualizing Exposures
Financial Networks IV. Analyzing and Visualizing ExposuresFinancial Networks IV. Analyzing and Visualizing Exposures
Financial Networks IV. Analyzing and Visualizing Exposures
ย 
Ijmsr 2016-05
Ijmsr 2016-05Ijmsr 2016-05
Ijmsr 2016-05
ย 
HDR Defence - Software Abstractions for Parallel Architectures
HDR Defence - Software Abstractions for Parallel ArchitecturesHDR Defence - Software Abstractions for Parallel Architectures
HDR Defence - Software Abstractions for Parallel Architectures
ย 
Opengl lec 3
Opengl lec 3Opengl lec 3
Opengl lec 3
ย 
Hpg2011 papers kazakov
Hpg2011 papers kazakovHpg2011 papers kazakov
Hpg2011 papers kazakov
ย 
Neural Networks - How do they work?
Neural Networks - How do they work?Neural Networks - How do they work?
Neural Networks - How do they work?
ย 
Gate-Cs 1995
Gate-Cs 1995Gate-Cs 1995
Gate-Cs 1995
ย 
Data structure-question-bank
Data structure-question-bankData structure-question-bank
Data structure-question-bank
ย 
Penn graphics
Penn graphicsPenn graphics
Penn graphics
ย 
Practical C++ Generative Programming
Practical C++ Generative ProgrammingPractical C++ Generative Programming
Practical C++ Generative Programming
ย 
Class[2][29th may] [javascript]
Class[2][29th may] [javascript]Class[2][29th may] [javascript]
Class[2][29th may] [javascript]
ย 
Resource to Performance Tradeoff Adjustment for Fine-Grained Architectures โ”€A...
Resource to Performance Tradeoff Adjustment for Fine-Grained Architectures โ”€A...Resource to Performance Tradeoff Adjustment for Fine-Grained Architectures โ”€A...
Resource to Performance Tradeoff Adjustment for Fine-Grained Architectures โ”€A...
ย 
RNN, LSTM and Seq-2-Seq Models
RNN, LSTM and Seq-2-Seq ModelsRNN, LSTM and Seq-2-Seq Models
RNN, LSTM and Seq-2-Seq Models
ย 
Al2ed chapter4
Al2ed chapter4Al2ed chapter4
Al2ed chapter4
ย 
MATHEON D-Day: Numerical simulation of integrated circuits for future chip ge...
MATHEON D-Day: Numerical simulation of integrated circuits for future chip ge...MATHEON D-Day: Numerical simulation of integrated circuits for future chip ge...
MATHEON D-Day: Numerical simulation of integrated circuits for future chip ge...
ย 
Asymptotic Notation and Data Structures
Asymptotic Notation and Data StructuresAsymptotic Notation and Data Structures
Asymptotic Notation and Data Structures
ย 
Predicting organic reaction outcomes with weisfeiler lehman network
Predicting organic reaction outcomes with weisfeiler lehman networkPredicting organic reaction outcomes with weisfeiler lehman network
Predicting organic reaction outcomes with weisfeiler lehman network
ย 
Review_Cibe Sridharan
Review_Cibe SridharanReview_Cibe Sridharan
Review_Cibe Sridharan
ย 
Auto encoding-variational-bayes
Auto encoding-variational-bayesAuto encoding-variational-bayes
Auto encoding-variational-bayes
ย 
Chap03[1]
Chap03[1]Chap03[1]
Chap03[1]
ย 

Similar to Core concepts of C++

Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)Ovidiu Farauanu
ย 
Technical Interview
Technical InterviewTechnical Interview
Technical Interviewprashant patel
ย 
cs8251 unit 1 ppt
cs8251 unit 1 pptcs8251 unit 1 ppt
cs8251 unit 1 pptpraveenaprakasam
ย 
Standardizing on a single N-dimensional array API for Python
Standardizing on a single N-dimensional array API for PythonStandardizing on a single N-dimensional array API for Python
Standardizing on a single N-dimensional array API for PythonRalf Gommers
ย 
Chapter 6
Chapter 6Chapter 6
Chapter 6Amit Gandhi
ย 
"Optimization of a .NET application- is it simple ! / ?", Yevhen Tatarynov
"Optimization of a .NET application- is it simple ! / ?",  Yevhen Tatarynov"Optimization of a .NET application- is it simple ! / ?",  Yevhen Tatarynov
"Optimization of a .NET application- is it simple ! / ?", Yevhen TatarynovFwdays
ย 
Toward Hybrid Cloud Serverless Transparency with Lithops Framework
Toward Hybrid Cloud Serverless Transparency with Lithops FrameworkToward Hybrid Cloud Serverless Transparency with Lithops Framework
Toward Hybrid Cloud Serverless Transparency with Lithops FrameworkLibbySchulze
ย 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.pptssuser0c24d5
ย 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.pptnilesh405711
ย 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.pptYashpalYadav46
ย 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.pptDevliNeeraj
ย 
C interview questions
C interview questionsC interview questions
C interview questionsSoba Arjun
ย 
Programming in C [Module One]
Programming in C [Module One]Programming in C [Module One]
Programming in C [Module One]Abhishek Sinha
ย 
JavaOne 2013: Memory Efficient Java
JavaOne 2013: Memory Efficient JavaJavaOne 2013: Memory Efficient Java
JavaOne 2013: Memory Efficient JavaChris Bailey
ย 
Go Faster With Native Compilation
Go Faster With Native CompilationGo Faster With Native Compilation
Go Faster With Native CompilationPGConf APAC
ย 
Go faster with_native_compilation Part-2
Go faster with_native_compilation Part-2Go faster with_native_compilation Part-2
Go faster with_native_compilation Part-2Rajeev Rastogi (KRR)
ย 
Go Faster With Native Compilation
Go Faster With Native CompilationGo Faster With Native Compilation
Go Faster With Native CompilationRajeev Rastogi (KRR)
ย 

Similar to Core concepts of C++ (20)

Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
ย 
Technical Interview
Technical InterviewTechnical Interview
Technical Interview
ย 
cs8251 unit 1 ppt
cs8251 unit 1 pptcs8251 unit 1 ppt
cs8251 unit 1 ppt
ย 
Standardizing on a single N-dimensional array API for Python
Standardizing on a single N-dimensional array API for PythonStandardizing on a single N-dimensional array API for Python
Standardizing on a single N-dimensional array API for Python
ย 
embedded C.pptx
embedded C.pptxembedded C.pptx
embedded C.pptx
ย 
Chapter 6
Chapter 6Chapter 6
Chapter 6
ย 
Software Engineering
Software EngineeringSoftware Engineering
Software Engineering
ย 
"Optimization of a .NET application- is it simple ! / ?", Yevhen Tatarynov
"Optimization of a .NET application- is it simple ! / ?",  Yevhen Tatarynov"Optimization of a .NET application- is it simple ! / ?",  Yevhen Tatarynov
"Optimization of a .NET application- is it simple ! / ?", Yevhen Tatarynov
ย 
Toward Hybrid Cloud Serverless Transparency with Lithops Framework
Toward Hybrid Cloud Serverless Transparency with Lithops FrameworkToward Hybrid Cloud Serverless Transparency with Lithops Framework
Toward Hybrid Cloud Serverless Transparency with Lithops Framework
ย 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
ย 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
ย 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
ย 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
ย 
PostgreSQL
PostgreSQLPostgreSQL
PostgreSQL
ย 
C interview questions
C interview questionsC interview questions
C interview questions
ย 
Programming in C [Module One]
Programming in C [Module One]Programming in C [Module One]
Programming in C [Module One]
ย 
JavaOne 2013: Memory Efficient Java
JavaOne 2013: Memory Efficient JavaJavaOne 2013: Memory Efficient Java
JavaOne 2013: Memory Efficient Java
ย 
Go Faster With Native Compilation
Go Faster With Native CompilationGo Faster With Native Compilation
Go Faster With Native Compilation
ย 
Go faster with_native_compilation Part-2
Go faster with_native_compilation Part-2Go faster with_native_compilation Part-2
Go faster with_native_compilation Part-2
ย 
Go Faster With Native Compilation
Go Faster With Native CompilationGo Faster With Native Compilation
Go Faster With Native Compilation
ย 

Recently uploaded

VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
ย 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
ย 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
ย 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
ย 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
ย 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
ย 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
ย 
Call Us โ‰ฝ 8377877756 โ‰ผ Call Girls In Shastri Nagar (Delhi)
Call Us โ‰ฝ 8377877756 โ‰ผ Call Girls In Shastri Nagar (Delhi)Call Us โ‰ฝ 8377877756 โ‰ผ Call Girls In Shastri Nagar (Delhi)
Call Us โ‰ฝ 8377877756 โ‰ผ Call Girls In Shastri Nagar (Delhi)dollysharma2066
ย 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
ย 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
ย 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
ย 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
ย 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
ย 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
ย 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
ย 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
ย 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examplesDr. Gudipudi Nageswara Rao
ย 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
ย 

Recently uploaded (20)

VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
ย 
โ˜… CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
โ˜… CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCRโ˜… CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
โ˜… CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
ย 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
ย 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
ย 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
ย 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
ย 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
ย 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
ย 
Call Us โ‰ฝ 8377877756 โ‰ผ Call Girls In Shastri Nagar (Delhi)
Call Us โ‰ฝ 8377877756 โ‰ผ Call Girls In Shastri Nagar (Delhi)Call Us โ‰ฝ 8377877756 โ‰ผ Call Girls In Shastri Nagar (Delhi)
Call Us โ‰ฝ 8377877756 โ‰ผ Call Girls In Shastri Nagar (Delhi)
ย 
young call girls in Green Park๐Ÿ” 9953056974 ๐Ÿ” escort Service
young call girls in Green Park๐Ÿ” 9953056974 ๐Ÿ” escort Serviceyoung call girls in Green Park๐Ÿ” 9953056974 ๐Ÿ” escort Service
young call girls in Green Park๐Ÿ” 9953056974 ๐Ÿ” escort Service
ย 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
ย 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
ย 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
ย 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
ย 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
ย 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
ย 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
ย 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
ย 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
ย 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
ย 

Core concepts of C++

  • 1. Restricted ยฉ 2017 Mentor Graphics Corporation 1 Core concepts of C++ Martin Ayvazyan 22/01/2019 Senior software/machine learning engineer
  • 2. Restricted ยฉ 2017 Mentor Graphics Corporation Contents ๏ฎ Memory management ๏ฎ Templates, Type deduction โ€“ decltype, auto ๏ฎ R-value references, Universal references, Move semantics, Perfect Forwarding ๏ฎ Smart pointers, STL ๏ฎ Concurrency โ€“ multitasking, multithreading (not completed yet) 2
  • 3. Restricted ยฉ 2017 Mentor Graphics Corporation Memory management ๏ฎ Intel 4004 (1971) - 4 bit ๏ฎ Intel 8008 (1978) - 8 bit ๏ฎ Intel 8086 (1978) - 16 bit ๏ฎ Intel 80286 (1982) โ€“ 16 bit + protected mode ๏ฎ Intel 80386 (1985) โ€“ 32 bit + protected mode 3
  • 4. Restricted ยฉ 2017 Mentor Graphics Corporation Memory management ๏ฎ Memory addressing โ€ข Real mode โ€ข Linear addressing โ€ข Segmentation โ€ข Protected mode โ€ข Segmentation โ€ข Paging 4
  • 5. Restricted ยฉ 2017 Mentor Graphics Corporation Memory management ๏ฎ Memory addressing - real mode All real mode memory addresses consist of a segment address plus an offset address: โ€ข the segment address (in one of the segment registers) defines the beginning address of any 64Kb memory segment โ€ข the offset address selects a location within the 64K byte memory segment ฯ’ = ฮฑ โˆ— 16 + ฮฒ where ฮฑฯต{๐‘๐‘ , ๐‘ ๐‘ , ๐‘‘๐‘ , ๐‘’๐‘ , ๐‘”๐‘ , ๐‘“๐‘ } 5
  • 6. Restricted ยฉ 2017 Mentor Graphics Corporation Memory management ๏ฎ Memory addressing โ€“ protected mode โ€ข From logic address ๏ƒ  Linear address (32 bit) โ€ข If paging is disabled ๏ƒ  Linear address ๏ƒง๏ƒจ Physical address Assembly of segment register in protected mode: 6 15 3 2 1 0 PRLTIIndex Selector TI โ€“ table index, if TI==0 ๏ƒ  GDT, if TI==1 ๏ƒ LDT PRL โ€“ request priority level (in case of CS CPL)
  • 7. Restricted ยฉ 2017 Mentor Graphics Corporation Memory management ๏ฎ Memory addressing โ€“ protected mode (TI=0) 7 GDTR GDT Descriptor Index byte5 byte4 byte3 byte2 byte1 byte0 Address Limit Address+Index*8
  • 8. Restricted ยฉ 2017 Mentor Graphics Corporation Memory management ๏ฎ Memory addressing โ€ข Protected mode The protected mode processors use a look up table to compute the physical address. Memory addressing is based on โ€˜Segment Descriptorsโ€™ that define a memory-region and assign its properties. 8 Type and access-rights Segment- Base[23..16] Word 3 Word 2 Segment-Base[15..0] Segment-Limit[15..0] Word 1 Word 0 Segment-base [31โ€ฆ24] FLAGS(G, DB, โ€ฆ)
  • 9. Restricted ยฉ 2017 Mentor Graphics Corporation Memory management ๏ฎ Memory addressing - Protected mode โ€ข Type and access-rights 9 P DPL S X C/D R/W A P = Present (1=yes, 0=no) DPL = Descriptor Privilege Level (00=supervisor, 11=user) S = System-segment (0=yes, 1=no) X = executable: 1=yes (i.e., code-segment), 0=no (i.e., data-segment) C/D = Conforming code (1=yes, 0=no) when X-bit equals 1 expands-Down (1=yes, 0=no) when X-bit equals 0 R/W = Readable (1=yes, 0=no) when X-bit equals 1 Writable (1=yes, 0=no) when X-bit equals 0 A = segment has been Accessed by the CPU (1=yes, 0=no)
  • 10. Restricted ยฉ 2017 Mentor Graphics Corporation Memory management ๏ฎ Memory addressing - Protected mode โ€ข Type and access-rights 10 S =1 S=0 I=0 E W I=1 C R TYPE(gates) A P โ€“ is the segment in memory DPL โ€“ description privilege level S โ€“ system descriptor(=1) or no(=0) I โ€“ data segment(=0), code segment(=1) E โ€“ common data segment(0) W โ€“ is writable (if (E) assert(W==1);) A โ€“ Access flag C โ€“ conform(=1), non-*(=0) segment R โ€“ Code segment can be read DPLP
  • 11. Restricted ยฉ 2017 Mentor Graphics Corporation Memory management ๏ฎ Paging / Virtual memory management 11 CR3 PD PDE PT PTE ฮฑ ฮฒ ฯ’ linear address Page
  • 12. Restricted ยฉ 2017 Mentor Graphics Corporation Memory management ๏ฎ Computer memory hierarchy 12 Registers Processor cache(L1, L2, โ€ฆ) RAM Hard drives 1 ns. 2 ns. 10 ns. 10 ms. < 1Kb 4 Mb 512-2048 Mb 200-1000Gb
  • 13. Restricted ยฉ 2017 Mentor Graphics Corporation Memory management ๏ฎ C++ memory storages (in general) โ€” Static โ€” Heap โ€” Stack 13
  • 14. Restricted ยฉ 2017 Mentor Graphics Corporation Memory management ๏ฎ C++ memory storages โ€“ static memory storage Possible problems of static objects initialization: โ€” static initialization order โ€˜fiascoโ€™ problem โ€“ here we have a 50%-50% chance of corrupting the program(if y would be constructed before x). 14 // f1.cpp #include โ€œT1.hโ€ T1 obj1; // f2.cpp #include โ€œT2.hโ€ T2 obj2; // T2.cpp #include โ€œT2.hโ€ T2::T2{ x.do_dmth(); }
  • 15. Restricted ยฉ 2017 Mentor Graphics Corporation Memory management ๏ฎ C++ memory storages โ€“ static memory storage Solution for the problem - Construct On First Use Idiom - i.e. replace the namespace-scope/global T1 object with a namespace- scope/global function f_obj() that returns the Fred object by reference: 15 // f1.cpp T1& get() { static T1* ptr = new T1(); return *ptr; } // f1.cpp T1& get() { static T1 ref; return ref; } ? need to be 100% sure our static object: (a) gets constructed prior to its first use (b) doesnโ€™t get destructed until after its last use.
  • 16. Restricted ยฉ 2017 Mentor Graphics Corporation Memory management ๏ฎ C++ memory storages โ€“ heap memory storage โ€” new operator to allocate an object in memory โ€” delete operator to deallocate an allocated object Try to avoid heap memory fragmentations as much as possible. Use placement new if you have enough knowledge about it: 16 void fn() { char memory[sizeof(T)]; void* p = memory; T* f = new(p) T(); // do smth. }
  • 17. Restricted ยฉ 2017 Mentor Graphics Corporation Memory management ๏ฎ C++ memory storages โ€“ heap memory storage / placement new 17 void fn() { char memory[sizeof(T)]; void* p = memory; T* f = new(p) T(); // do smth. } void fn() { char memory[sizeof(T)]; void* p = memory; T* f = new(p) T(); // do smth. f->~T(); }
  • 18. Restricted ยฉ 2017 Mentor Graphics Corporation Memory management ๏ฎ C++ memory storages โ€“ โ€˜stackโ€™ memory storage โ€” Stack variables are local in nature. โ€” There is a limit (varies with OS) on the size of variables that can be stored on the stack. โ€” The stack grows and shrinks as functions push and pop local variables โ€” There is no need to manage the memory yourself, variables are allocated and freed automatically โ€” Stack variables only exist while the function that created them, is running 18
  • 19. Restricted ยฉ 2017 Mentor Graphics Corporation Memory management ๏ฎ C++ memory storages โ€“ stack vs heap 19 Stack Heap very fast access (relatively) slower access don't have to explicitly de-allocate variables no guaranteed efficient use of space limit on stack size (OS-dependent) no limit on memory size local variables only variables can be accessed globally space is managed efficiently by CPU, memory will not become fragmented allocated memory must be managed variables cannot be resized variables can be resized using realloc()
  • 20. Restricted ยฉ 2017 Mentor Graphics Corporation Memory management ๏ฎ Structure Padding โ€ข Architecture of a computer processor is such a way that it can read 1 word (4 byte in 32 bit processor) from memory at a time. โ€ข To make use of this advantage of processor, data are always aligned as 4 bytes package which leads to insert empty addresses between other memberโ€™s address. โ€ข Because of this size of the structure is always not same as what we think. โ€ข In order to align the data in memory, one or more empty bytes are inserted between memory addresses which are allocated for other structure members while memory allocation. 20
  • 21. Restricted ยฉ 2017 Mentor Graphics Corporation Memory management ๏ฎ Structure Padding 21 struct A {}; struct B {bool b}; struct C {bool b; int x;}; struct C {bool b1, b2; int x;}; struct C {bool b1; int x; bool b2}; [](){}; [x=true, y=2, z= true](){}; [x=true, y=2, z= true](){}; std::tuple<bool, int> std::tuple<bool, bool, int> std::tuple<bool,int, bool> std::function<void()>
  • 22. Restricted ยฉ 2017 Mentor Graphics Corporation Memory management ๏ฎ False sharing 22 class T { int x1, x2;}; static T obj; int f() { int sum=0; for (i=0;i<131313; ++i) sum +=obj.x1; return sum; } void g() { for (i=0;i<131313; ++i) ++obj.x2; } When f and g are running concurrently sum may need re-read x1 from main memory event though concurrent modification of x2 does not affect on x1.
  • 23. Restricted ยฉ 2017 Mentor Graphics Corporation Memory management ๏ฎ False sharing 23
  • 24. Restricted ยฉ 2017 Mentor Graphics Corporation Memory management ๏ฎ Value categories in C++ Each C++ expression is characterized by two independent properties: a type and a value. Each expression has some non-reference type and each expression belongs to a value category. โ€ข C++98 An expression is either an: โ€ข lvalue โ€“ occupies some identifiable location in memory โ€ข rvalue โ€“ !lvalue โ€ข C++11 โ€ข lvalue โ€ข rvalue โ€ข xvalue โ€ข prvalue โ€ข glvalue 24
  • 25. Restricted ยฉ 2017 Mentor Graphics Corporation Memory management ๏ฎ Value categories in C++11 Two properties of expressions โ€ข Can be moved from Move constructor, move โ€˜=โ€˜operator, or another function overload that implements move semantics can bind to the expression. โ€ข Has identity Itโ€™s possible to determine whether the expression refers to the same entity as another expression, such as by comparing addresses of the objects or the functions they identify(obtained directly or indirectly). 25
  • 26. Restricted ยฉ 2017 Mentor Graphics Corporation Memory management ๏ฎ Value categories in C++11 โ€ข glvalue - has identity. Is either lvalue or xvalue. โ€ข rvalue โ€“ can be moved from. Is either prvalue or xvalue. โ€ข lvalue โ€“ has identity and canโ€™t be moved from. { the name of a variable, a function, function call whose return type is lvalue(++i), assignment and compound assignment, built-in comma expression where the second operand is lvalue, a ? b : c(lvalues), string literal, static_cast<T&> } โ€ข xvalue โ€“ has identity and can be moved from. { std::move, static_cast<T&&>, the member of object like a.m(where a is an rvalue and m is non-static data member of non-reference type) } โ€ข prvalue- does not identity and canโ€™t be moved from. {literal, i++, expr. Whose return type non-ref, built-in address-of expression, static_cast<int> } 26
  • 27. Restricted ยฉ 2017 Mentor Graphics Corporation Memory management ๏ฎ Value categories 27 expression rvalue glvalue prvalue xvalue lvalue
  • 28. Restricted ยฉ 2017 Mentor Graphics Corporation Memory management ๏ฎ Bitfields 28 struct S { bool b1: 1, bool b2: 1, โ€ฆ bool b8: 1 }; union { struct S { bool b1: 1, bool b2: 1, โ€ฆ bool b8: 1 }; bool dummy; };
  • 29. Restricted ยฉ 2017 Mentor Graphics Corporation Memory management ๏ฎ Things need to attention โ€” const_cast โ€” (a+b)-c != a+(b-c) โ€” stack and realloc โ€” using compile-time unknown expression to define size of stakโ€™s objects โ€” taking address of a bitfield โ€” size of an array like arr[N] known at compile time! (T(&)[N]) 29
  • 30. Restricted ยฉ 2017 Mentor Graphics Corporation Templates / Type deduction โ€“ auto and decltype ๏ฎ Type deduction for templates MyT x; const MyT& y = x; ๐‘ก๐‘’๐‘š๐‘๐‘™๐‘Ž๐‘ก๐‘’ < ๐‘๐‘™๐‘Ž๐‘ ๐‘  ๐‘‡ > ๐‘ฃ๐‘œ๐‘–๐‘‘ ๐‘“ ๐‘‡2 ๐‘Ž๐‘Ÿ๐‘” โ€ฆ โ€” ๐‘ก๐‘’๐‘š๐‘๐‘™๐‘Ž๐‘ก๐‘’ < ๐‘๐‘™๐‘Ž๐‘ ๐‘  ๐‘‡ > ๐‘ฃ๐‘œ๐‘–๐‘‘ ๐‘“ ๐‘‡ ๐‘Ž๐‘Ÿ๐‘” โ€ฆ ๏ƒ  f(x), f(y) T2, T2 ? โ€” ๐‘ก๐‘’๐‘š๐‘๐‘™๐‘Ž๐‘ก๐‘’ < ๐‘๐‘™๐‘Ž๐‘ ๐‘  ๐‘‡ > ๐‘ฃ๐‘œ๐‘–๐‘‘ ๐‘“ ๐‘‡& ๐‘Ž๐‘Ÿ๐‘” โ€ฆ ๏ƒ  f(x), f(y) T2, T2 ? โ€” ๐‘ก๐‘’๐‘š๐‘๐‘™๐‘Ž๐‘ก๐‘’ < ๐‘๐‘™๐‘Ž๐‘ ๐‘  ๐‘‡ > ๐‘ฃ๐‘œ๐‘–๐‘‘ ๐‘“ ๐‘๐‘œ๐‘›๐‘ ๐‘ก ๐‘‡& ๐‘Ž๐‘Ÿ๐‘” โ€ฆ ๏ƒ  f(x), f(y) T2, T2 ? โ€” ๐‘ก๐‘’๐‘š๐‘๐‘™๐‘Ž๐‘ก๐‘’ < ๐‘๐‘™๐‘Ž๐‘ ๐‘  ๐‘‡ > ๐‘ฃ๐‘œ๐‘–๐‘‘ ๐‘“ ๐‘‡&& ๐‘Ž๐‘Ÿ๐‘” โ€ฆ ๏ƒ  f(x), f(y) T2, T2 ? โ€” ๐‘ก๐‘’๐‘š๐‘๐‘™๐‘Ž๐‘ก๐‘’ < ๐‘๐‘™๐‘Ž๐‘ ๐‘  ๐‘‡ > ๐‘ฃ๐‘œ๐‘–๐‘‘ ๐‘“ ๐‘‡ ๐‘Ž๐‘Ÿ๐‘” โ€ฆ ๏ƒ  f(&x), f(&y) T2, T2 ? 30
  • 31. Restricted ยฉ 2017 Mentor Graphics Corporation Templates / Type deduction โ€“ auto and decltype ๏ฎ Type deduction for templates MyT x; const MyT& y = x; ๐‘ก๐‘’๐‘š๐‘๐‘™๐‘Ž๐‘ก๐‘’ < ๐‘๐‘™๐‘Ž๐‘ ๐‘  ๐‘‡ > ๐‘ฃ๐‘œ๐‘–๐‘‘ ๐‘“ ๐‘‡2 ๐‘Ž๐‘Ÿ๐‘” โ€ฆ โ€” ๐‘ก๐‘’๐‘š๐‘๐‘™๐‘Ž๐‘ก๐‘’ < ๐‘๐‘™๐‘Ž๐‘ ๐‘  ๐‘‡ > ๐‘ฃ๐‘œ๐‘–๐‘‘ ๐‘“ ๐‘‡ ๐‘Ž๐‘Ÿ๐‘” โ€ฆ ๏ƒ  f(x), f(y) T2=MyT, T2=MyT โ€” ๐‘ก๐‘’๐‘š๐‘๐‘™๐‘Ž๐‘ก๐‘’ < ๐‘๐‘™๐‘Ž๐‘ ๐‘  ๐‘‡ > ๐‘ฃ๐‘œ๐‘–๐‘‘ ๐‘“ ๐‘‡& ๐‘Ž๐‘Ÿ๐‘” โ€ฆ ๏ƒ  f(x), f(y) T2=MyT, T2=const MyT โ€” ๐‘ก๐‘’๐‘š๐‘๐‘™๐‘Ž๐‘ก๐‘’ < ๐‘๐‘™๐‘Ž๐‘ ๐‘  ๐‘‡ > ๐‘ฃ๐‘œ๐‘–๐‘‘ ๐‘“ ๐‘๐‘œ๐‘›๐‘ ๐‘ก ๐‘‡& ๐‘Ž๐‘Ÿ๐‘” โ€ฆ ๏ƒ  f(x), f(y) T2=MyT, T2=MyT โ€” ๐‘ก๐‘’๐‘š๐‘๐‘™๐‘Ž๐‘ก๐‘’ < ๐‘๐‘™๐‘Ž๐‘ ๐‘  ๐‘‡ > ๐‘ฃ๐‘œ๐‘–๐‘‘ ๐‘“ ๐‘‡&& ๐‘Ž๐‘Ÿ๐‘” โ€ฆ ๏ƒ  f(x) T2=MyT&, T2=const MyT& โ€” ๐‘ก๐‘’๐‘š๐‘๐‘™๐‘Ž๐‘ก๐‘’ < ๐‘๐‘™๐‘Ž๐‘ ๐‘  ๐‘‡ > ๐‘ฃ๐‘œ๐‘–๐‘‘ ๐‘“ ๐‘‡ ๐‘Ž๐‘Ÿ๐‘” โ€ฆ ๏ƒ  f(&x), f(&y) T2=MyT*, T2=const MyT* 31
  • 32. Restricted ยฉ 2017 Mentor Graphics Corporation Templates / Type deduction โ€“ auto and decltype ๏ฎ Type deduction for templates template <class T> void f(const T& arg) { T par = arg; par.non_const_fn(); } template <class T> void f(T& arg) { T par = arg; par.non_const_fn(); } template <class T> void f(T arg) { T par = arg; par.non_const_fn(); } 32
  • 33. Restricted ยฉ 2017 Mentor Graphics Corporation Templates / Type deduction โ€“ auto and decltype ๏ฎ auto 33 struct S { S(int x) :m(x){} int m; }; S operatorโ€โ€_ma13 (unsigned long long x) { return S(static_cast<int>(x)); } auto x1 = 13_ma13; auto x2(13_ma13); auto x3 = {13_ma13}; auto x4 {13_ma13}; auto x5 = {13_ma13, 13_ma13}; auto x6 {13_ma13, 13_ma13}; auto x7 ={13_ma13, 13}; template <class T> void f(T); f({13_ma13}); f({13_ma13, 13_ma13}); ? ? ? ? ? ? ? ? ?
  • 34. Restricted ยฉ 2017 Mentor Graphics Corporation Templates / Type deduction โ€“ auto and decltype ๏ฎ auto 34 auto x1 = 13_ma13; auto x2(13_ma13); auto x3 = {13_ma13}; auto x4 {13_ma13}; auto x5 = {13_ma13, 13_ma13}; auto x6 {13_ma13, 13_ma13}; auto x7 ={13_ma13, 13}; template <class T> void f(T); f(13_ma13); f({13_ma13}); f({13_ma13, 13_ma13}); S S std::initializer_list<S> S std::initializer_list<S> error โ€ฆ. (add โ€˜=โ€˜ before the {) std::initializer_list<S> S error โ€“ cannot deduce T error โ€“ cannot deduce T
  • 35. Restricted ยฉ 2017 Mentor Graphics Corporation Templates / Type deduction โ€“ auto and decltype ๏ฎ auto 35 auto f() { return 13_ma13;} auto fn1 = [] (auto s) {โ€ฆ} auto fn2 = [] (const auto& s) {โ€ฆ} f1(13_ma13); f1({13_ma13}); f2({13_ma13}); ? cannot ?
  • 36. Restricted ยฉ 2017 Mentor Graphics Corporation Templates / Type deduction โ€“ auto and decltype ๏ฎ auto 36 auto f() { return 13_ma13;} auto fn1 = [] (auto s) {โ€ฆ} auto fn2 = [] (const auto& s) {โ€ฆ} f1(13_ma13); f1({13_ma13}); f2({13_ma13}); S a braced-enclosed list does not provide return value a braced-enclosed list does not provide return value
  • 37. Restricted ยฉ 2017 Mentor Graphics Corporation Templates / Type deduction โ€“ auto and decltype ๏ฎ auto โ€ข In general itโ€™s the same as template type deduction. The main difference is that auto assumes that a braced initializers represents a std::initializer_list, but TTD-doesnโ€™t. โ€ข Auto in function return type or a lambda parameter implies TTD, not auto type deduction. 37
  • 38. Restricted ยฉ 2017 Mentor Graphics Corporation Templates / Type deduction โ€“ auto and decltype ๏ฎ auto and decltype 38 int x[10]; auto f1(int i) { return x[i];} decltype(auto) f2(int i) { return x[i];} f1(0) = 4; f2(0) = 4
  • 39. Restricted ยฉ 2017 Mentor Graphics Corporation Templates / Type deduction โ€“ auto and decltype ๏ฎ decltype โ€ข Decltype almost always yields the type of expression without modification. โ€ข For lvaluesโ€™ of type T decltype always reports a T& 39
  • 40. Restricted ยฉ 2017 Mentor Graphics Corporation Templates / Type deduction โ€“ auto and decltype ๏ฎ decltype 40 decltype(auto) f() { bool b; โ€ฆ return (b); } UNDEFINED BEHAVIOR!!!!!
  • 41. Restricted ยฉ 2017 Mentor Graphics Corporation Templates / Type deduction โ€“ auto and decltype ๏ฎ partial specialization ๏ฎ static_assert 41 template <class T> void g(T) {cout<<โ€œAโ€;} template <> void g<int>(int){cout<<โ€œBโ€;} template <class T> void f(T) { static_assert(std::is_same_v<T, int>); } g(1); // B g(1.); // A f(1); // fine f(1.); //compile error
  • 42. Restricted ยฉ 2017 Mentor Graphics Corporation Templates / Type deduction โ€“ auto and decltype ๏ฎ std::enable_if 42 template<class T, typename = void> class A{}; template<class T> class A<T, typename = std::enable_if_t<std::is_fundamental_v<T>> {}; template<class T, typename = void> class A{}; template<class T> class A<T, typename = std::enable_if_t<std::is_fundamental_v<T>> {}; template<class T> class A<T, typename = std::enable_if_t<std::is_integral_v<T>> {};
  • 43. Restricted ยฉ 2017 Mentor Graphics Corporation Templates / Type deduction โ€“ auto and decltype class D {virtual void f(){}}; template<class T> class D { virtual void f(){}; }; template<class T> class D { template <class T2=T> virtual void f(){}; }; 43 ? ? ?
  • 44. Restricted ยฉ 2017 Mentor Graphics Corporation Templates / Type deduction โ€“ auto and decltype class D {virtual void f(){}}; template<class T> class D { virtual void f(){}; }; template<class T> class D { template <class T2=T> virtual void f(){}; }; 44 OK OK Error โ€“ virtual is not allowed in a function template declaration
  • 45. Restricted ยฉ 2017 Mentor Graphics Corporation R-value references, Universal references, Move semantics, Perfect Forwarding ๏ฎ R-value references - && ๏ฎ Universal references - && ๏ฎ Move semantics - via std::move ๏ฎ Perfect forwarding โ€“ via std::forward 45
  • 46. Restricted ยฉ 2017 Mentor Graphics Corporation R-value references, Universal references, Move semantics, Perfect Forwarding ๏ฎ R-value references 46 void f(S&& obj) {/โ€ฆ/} f(13_ma13); S x = 13_ma13; f(x); fine an rvalue ref. cant be bound to an lvalue
  • 47. Restricted ยฉ 2017 Mentor Graphics Corporation R-value references, Universal references, Move semantics, Perfect Forwarding ๏ฎ R-value references 47 struct S { void f1() & {} void f2() && {} }; auto x = 13_ma13; x.f1(); x.f2(); fine error- function canโ€™t be called on lvalue
  • 48. Restricted ยฉ 2017 Mentor Graphics Corporation R-value references, Universal references, Move semantics, Perfect Forwarding ๏ฎ Universal referances 48 template <class T> void f(T&&) {โ€ฆ} auto&& s = 13_ma13; If a function template parameter has type T&& for a deduced type, or an object is declared using auto&&, the paramet or object is a UR. UR correspond to rvalue if they are initialized with rvalues. The same for lvalue.
  • 49. Restricted ยฉ 2017 Mentor Graphics Corporation R-value references, Universal references, Move semantics, Perfect Forwarding ๏ฎ Move semantics 49 std::vector<int> x{1,2,3,4}; std::vector<int> y=std::move(x); assert(x.empty()); assert(y.size() == 4); //possible impl. template<typename T> constexpr typename std::remove_reference<T>::type&& move(T&& t) noexcept { return static_cast<typename std::remove_reference<T>::type&&>(t); }
  • 50. Restricted ยฉ 2017 Mentor Graphics Corporation R-value references, Universal references, Move semantics, Perfect Forwarding ๏ฎ Perfect Forwarding 50 template <class T> void f1(T&& val) { f(val); } template <class T> void f2(T&& val) { f(std::forward<T>(val)); } S s = 13_ma13; f1(s); //in f is passed ? f1(13_ma13); // in f is passed ? f2(s); // in f is passed ? f2(13_ma13); // in f is passed ?
  • 51. Restricted ยฉ 2017 Mentor Graphics Corporation R-value references, Universal references, Move semantics, Perfect Forwarding ๏ฎ Perfect Forwarding 51 void f(S&) {cout<<โ€œlvalueโ€;} void f(S&&) {cout<<โ€œrvalueโ€;} template <class T> void f1(T&& val) { f(val); } template <class T> void f2(T&& val) { f(std::forward<T>(val)); } S s = 13_ma13; f1(s); //lvalue f1(13_ma13); // lvalue f2(s); // lvalue f2(13_ma13); // rvalue
  • 52. Restricted ยฉ 2017 Mentor Graphics Corporation R-value references, Universal references, Move semantics, Perfect Forwarding ๏ฎ Use std::move on rvalue referances, std::forward on universal referances. ๏ฎ Never use std::move or std::forward to local objects it they would otherwise be eligible for the RVO. 52
  • 53. Restricted ยฉ 2017 Mentor Graphics Corporation R-value references, Universal references, Move semantics, Perfect Forwarding ๏ฎ Variadic templates 53 template<typename โ€ฆ Args> void f(Args&& โ€ฆargs) { f1(std::forward<Args>(args)โ€ฆ); } template<typename โ€ฆ Args> class A { public: void f(Args&&โ€ฆ args) { f1(std::forward<Args>(args)โ€ฆ); } };
  • 54. Restricted ยฉ 2017 Mentor Graphics Corporation R-value references, Universal references, Move semantics, Perfect Forwarding template <class T> struct A { void f(T&& obj) {} template <class T2 = T> void f2(T2&& obj) {} }; 54 A<S> obj; S obj = 13_ma13; obj.f(13_ma13); obj.f(s); obj.f2(13_ma13); obj.f2(s); ? ? ? ?
  • 55. Restricted ยฉ 2017 Mentor Graphics Corporation R-value references, Universal references, Move semantics, Perfect Forwarding template <class T> struct A { void f(T&& obj) {} template <class T2 = T> void f2(T2&& obj) {} }; 55 A<S> obj; S obj = 13_ma13; obj.f(13_ma13); obj.f(s); obj.f2(13_ma13); obj.f2(s); OK error OK OK
  • 56. Restricted ยฉ 2017 Mentor Graphics Corporation Smart pointers, STL ๏ฎ Smart pointers โ€ข unique_ptr โ€ข shared_ptr โ€ข weak_ptr 56
  • 57. Restricted ยฉ 2017 Mentor Graphics Corporation Smart pointers, STL ๏ฎ Smart pointers โ€“ unique_ptr โ€ข Movable, non-copyable 57 template <typename T, typename D> class unique_ptr; template<typename T, typename D> class unique_ptr<T[], D>; template <typename T, typeneme โ€ฆ Args> unique_ptr make_unique(Args&&โ€ฆ args);
  • 58. Restricted ยฉ 2017 Mentor Graphics Corporation Smart pointers, STL ๏ฎ Smart pointers โ€“ shared_ptr โ€ข Movable, copyable 58 template <typename T> class shared_ptr; template<class T, typename โ€ฆ Args> shared_ptr<T> make_shared(Args&& โ€ฆ args);
  • 59. Restricted ยฉ 2017 Mentor Graphics Corporation Smart pointers, STL ๏ฎ Smart pointers โ€“ weak_ptr โ€ข Movable, copyable 59 template<class T> class weak_ptr { โ€ฆ shared_ptr<T> lock(); โ€ฆ };
  • 60. Restricted ยฉ 2017 Mentor Graphics Corporation Smart pointers, STL ๏ฎ STL โ€ข std::array โ€ข std::unordered_set/map โ€ข std::unordered_multiset/multimap โ€ข std::emplace for all containers โ€ข Parallel execution support for STL algorithms 60
  • 61. Restricted ยฉ 2017 Mentor Graphics Corporation Concurrency โ€“ multitasking, multithreading ๏ฎ multi-threading ๏ฎ multi-tasking ๏ฎ std::mutex ๏ฎ std::condition_variable ๏ฎ std::atomic ๏ฎ std::thread ๏ฎ std::future ๏ฎ std::async 61
  • 62. Restricted ยฉ 2017 Mentor Graphics Corporation 62 Thank you!