SlideShare a Scribd company logo
NAP Talks
C++14: Modern Programming for Demanding Times
Speaker: Carlos Miguel Ferreira
Position: PhD Student and IT Researcher
Contact: carlosmf.pt@gmail.com
Layout
1st Part – Some History
➔
Some background about C++
➔
Philosophy
➔
The International Standard
➔
Boost
➔
Standard Template Library
Break
Time
2 60/
2nd Part – The Basics
➔
Standard Types
➔
Methods
➔
Pointers and References
➔ Lambda Functions
➔ Casting in C++
➔
Structures and Classes
4th Part - Extreme C++
➔
Automatic Type Deduction
➔ Templates & Meta-Programming
➔ SFINAE rule
➔
Type Traits
3rd Part – Increased complexity
➔
Exceptions
➔
Smart Pointers
➔
Generic Containers
➔
Generic Algorithms
➔
Multi-threading
➔ Synchronization
1st Part 3 60/
C++14
History, Philosophy and
Standards
Why waste time learning
when ignorance is instantaneous?
– Hobbes
C++ History 4 60/
The author: Bjarne Stroustrup
Development starts by the around 1978, during his PhD at
Churchill College, Cambridge.
Took inspiration from Simula
➔
Known as the first language to support Object Oriented
Programming.
➔ But it was to slow for practical use...
In the beginning, It was called “C with Classes”
First compiler: Cfront (derived from Cpre)
➔
Under the hood, just a translator
●
Translating classes to pure C.
●
Self-hosting compiler
●
Supported classes, basic inheritance, inlining, default arguments
●
It did not officially supported the OO paradigm...
C++ History 5 60/
In 1983:
➔
The language changes the name to C++
➔
First implementation in use
In 1986:
➔
First commercial release (Cfront PC port)
➔
But still no available standard…
In 1987:
➔
GNU C++ compiler v0.9 beta is released by Richard Stallman.
➔ New features were added:
●
Virtual functions, overloading, references…
●
It could then be called an Object Oriented Programming
Language!
●
“The C++ Programming Language 1st
Ed.” book is released.
Free Software
Foundation Founder
C++ Philosophy 6 60/
Some of the philosophical rules that guide the C++ language development.
Not All! Know more from the paper “Evolving a language in and for the real world: C++ 1991-2006”
DOI: 10.1145/1238844.1238848
General
➔
C++ evolution must be driven by real problems.
➔
Every feature must have a reasonably obvious
implementation.
➔
C++ is a language, not a complete system.
➔
Don’t try to force people to use a specific
programming style.
Technical
➔
Locality is good.
➔
Avoid order dependencies.
➔
Preprocessor usage should be eliminated.
Low-Level Support
➔
Leave no room for a lower-level language below
C++ (except assembler).
➔
What you don’t use, you don’t pay for (zero-
overhead rule).
Design
➔
Say what you mean.
➔
Provide facilities for program organization.
➔
All features must be affordable.
C++ International Standards (ISO) 7 60/
What are Technical Standards?
Even better, what are International Standards?
Technical Standards
A technical standard is an established norm or
requirement in regard to technical systems. It is
usually a formal document that establishes
uniform engineering or technical criteria,
methods, processes and practices. In contrast, a
custom, convention, company product, corporate
standard, etc. that becomes generally accepted
and dominant is often called a de facto standard.
International Standards
International standards are one way of
overcoming technical barriers in international
commerce caused by differences among
technical regulations and standards developed
independently and separately by each nation,
national standards organization, or company.
Technical barriers arise when different groups
come together, each with a large user base,
doing some well established thing that between
them is mutually incompatible. Establishing
international standards is one way of preventing
or overcoming this problem.
According to Wikipedia...
C++ International Standards (ISO) 8 60/
The C++ Standard intends to:
➔
Create an abstraction of a general computing machine.
➔
Defines a very rigid technical specification, asserting code portability.
●
It Defines Behaviours, and more important Undefined Behaviours!
➔
Defines the Standard Library (std::) behaviour. Very Important!
●
You will see lots of "the behaviour is defined/undefined" indications, in the C++ reference
manuals.
➔ It gave us the Standard Template Library (STL)
The C++ Standard is maintained by a Committee:
➔
Composed by companies, academics and freelancers representatives.
➔ Very strict review of new additions to the standard.
➔ Promote C++ learning and adoption.
➔
They usually take some time…
●
First Commercial was release in 1987...
●
But the 1st
ISO only came out in 1998! (C++98: ISO/IEC 14882:1998)
C++ International Standards (ISO) 9 60/
C++98
➔
The first one
➔
1998
➔
ISO/IEC 14882:1998
➔
Single Threading by design.
C++03
➔
2003
➔
ISO/IEC 14882:2003
Existing C++ Standards
C++11
➔
2011
➔
ISO/IEC 14882:2011
➔
Multi-threaded by design
C++14
➔
2014
➔
ISO/IEC 14882:2014
C++17
➔
Expected 2017
Old and quirky New and Improved!
vector<vector<int> >
vector_of_int_vectors;
The lack of a space between the “> >”
was an error in C++03. The compiler
got confused with the “>>” operator.
More information at: https://isocpp.org/std/status
C++ Boost→ 10 60/
“Boost provides free peer-reviewed portable C++
source libraries.
We emphasize libraries that work well with the C++
Standard Library. Boost libraries are intended to be
widely useful, and usable across a broad spectrum
of applications. The Boost license encourages both
commercial and non-commercial use.
We aim to establish "existing practice" and provide
reference implementations so that Boost libraries
are suitable for eventual standardization. Ten Boost
libraries are included in the C++ Standards
Committee's Library Technical Report (TR1) and in
the new C++11 Standard. C++11 also includes several
more Boost libraries in addition to those from TR1.
More Boost libraries are proposed for
standardization in C++17.”
The Boost Libraries
➔
First release in 1998
➔
After the Standard Library, Boost is
the most important library available
to the C++ development community.
➔
Many of its own libraries made their
way to the C++11 standard!
●
Arrays
●
Regular Expressions
●
Complex numbers
➔
More will be added to C++17.
●
Filesystem
More information at: https://www.boost.org
C++ Standard Template Library→ 11 60/
What is the Standard Template Library (STL)?
➔ A set of Generalized Structures
➔ A set of Algorithms for Generalized
Structures
●
The key here is generalized.
●
STL does not deal in specifics!
➔ Separates algorithms from storage in a way
that is classical (as in math) but not object
oriented.
➔
It separates policy decisions of algorithms,
such as sorting and search criteria, from the
container, and the element class.
➔
Standardized Structures and Behaviours!
Some of the available containers
<array>
<list>
<map>
<queue>
<set>
<stack>
<vector>
and many others...
More information at: http://en.cppreference.com/w/cpp/container
Later, I will talk more about
these containers
The result?
Unsurpassed flexibility and performance.
C++ 14 12 60/
This talk is about the C++14 Standard.
Threads
Containers
Lambda
Expressions
Automatic
Type deduction
Ranged for
Loops
Move
Constructors
Initialization
Lists
Type Traits
Smart
Pointers
2nd Part 13 60/
C++14
Lets start with the basics!
A programmer is a machine
for turning caffeine into code.
– A programmer
Including 14 60/
C++ has many new features not present in C
To maintain compatibility and to keep C libraries usable in C++ environments, the
standard provides compatibility header files:
<cassert> (assert.h) → C Diagnostics Library
<cctype> (ctype.h) → Character handling functions
<cerrno> (errno.h) → C Errors
<csignal> (signal.h) → C library to handle signals
<cstdio> (stdio.h) → C library to perform Input/Output operations
<cstdlib> (stdlib.h) → C Standard General Utilities Library
<cstring> (string.h) → C Strings
<ctgmath> (tgmath.h) → Type-generic math
<ctime> (time.h) → C Time Library
<cuchar> (uchar.h) → Unicode characters
<cwchar> (wchar.h) → Wide characters
<cwctype> (wctype.h) → Wide character
The C precedes the name of the classical C header.
More information at: http://en.cppreference.com/w/cpp/header
The main function. 15 60/
Global method term used to catch
unhandled exceptions.
Uncaught exception handler is registered.
Program arguments are caught and
std::strings are created.
Don’t worry about the Exception
I will talk about them later...
std::exception is throwed.
Namespaces 16 60/
Same method declared in different
namespaces.
Result:
Namespaces are great for code management!
Explicitly choose the namespace
Or specifically state your intentions
The std:: namespace contains every C++
standardized type, function and object.
Standard Types → void, bool and char 17 60/
The C++ 14 standard specifies the behaviour for a set of types.
➔
Most are from C99 standard.
➔
Fundamental types are not inside the namespace std::
Void type
➔ void
➔ nullptr literal
➔ std::nullptr_t type
Boolean Type
➔ bool → true or false
Character types
➔ char (signed/unsigned)
➔ wchar_t
➔ char16_t
➔ char32_t
Special types!
Standard dictactes there cannot be void type arrays.
void size is undefined!
The most efficiently processed character representation on the
target system (size undefined).
The necessary size to represent any kind of supported character
code unit (32bits for Unicode systems).
Large enough for:
●
UTF-16
●
UTF-32
Size is 1 byte
Standard Types i→ nteger, float and double 18 60/
Floating point types (IEEE-754)Integer types
➔ float → single precision
➔ double → double precision
➔ long double → extended precision
int (signed/unsigned)→ 2 bytes at least
➔ short –----→ 2 bytes at least
➔ long –----→ 4 bytes at least
➔ long long –----→ 8 bytes at least
More information at: http://en.cppreference.com/w/cpp/language/types
Defined by Standard
➔
Sizes are undefined.
➔
Instead, the standard defines the precision
behaviour, and special values.
●
Infinity
●
Negative Zero
●
Not-a-Number (NaN)
➔
Arithmetic operations are also specified
Standard Types Fixed Width Integers→ 19 60/
Fixed Width Integer types
(all within std::)
int8_t
int16_t
int32_t
int64_t
int_fast8_t
int_fast16_t
int_fast32_t
int_fast64_t
int_least8_t
int_least16_t
int_least32_t
int_least64_t
intmax_t
intptr_t
More information at: http://en.cppreference.com/w/cpp/types/integer
uint8_t
uint16_t
uint32_t
uint64_t
uint_fast8_t
uint_fast16_t
uint_fast32_t
uint_fast64_t
uint_least8_t
uint_least16_t
uint_least32_t
uint_least64_t
uintmax_t
uintptr_t
➢
Integer type with width of
exactly 8, 16, 32 and 64 bits
Signed Unsigned
➢
Fastest integer type with
width of at least 8, 16, 32 and
64 bits
➢
Smallest integer type with
width of at least 8, 16, 32 and
64 bits
➢
Maximum width integer type
➢ Integer type capable of holding
a pointer
Standard Types Enumerators→ 20 60/
Specifying the enum memory size
➔
This is a hidden inheritance
Enumerations declarations
➔
By default, the size is int
Get the defined enumerations
using the :: scope resolution
operator
Standard Types Strings→ 21 60/
Available at <string>
Regular expressions at <regex>
➔ String → char
➔ wstring → wchar_t
➔ u16string → char16_t
➔ u32string → char32_t
More information at: http://en.cppreference.com/w/cpp/header/string
These
types
use these
fundamental
types
underneath
Initializations
Attributions
Concatenations
Iterations
Compatibility
Methods 22 60/
Result
Method Overloading
The names are equal
➔
Different signatures for equivalent behaviours
➔
Keep code clean, elegant!
➔
No method naming Hell!
Pointers, References and the const specifier 23 60/
Pointers and References
(prefer references, unless working with C)
Pointers are useful but:
➔
Is there really an object at address 0x123?
➔
Good code always checks if memory is accessible.
➔
Memory checks cost processing time...
➔ A pointer value could be NULL
References provide assurance:
➔
Object must exists! (sort of)
The const type qualifier provides robustness:
➔
Forbids state modification
Yes, you can always hack it, but seriously… don’t…
➔
Always avoid this
●
Unless you’re using a buggy library…
➔
Never ever in your life do this!!!
●
You have been warned!
●
The segfault Hell awaits you, if you ignore...
Lambda functions 24 60/
Also called anonymous functions
Lambda functions are useful to:
➔
Keep code localized and contained
➔
Pass callbacks to functions, event managers or threads!
Lambda signature
➔ [ capture-list ] ( params ) mutable → ret { body }
Capture List
➔
[a,&b] → a captured by value and b is captured by reference.
➔
[&] → captures all automatic variables odr-used in the body of the lambda by reference
➔
[=] → captures all automatic variables odr-used in the body of the lambda by value
➔
[] → captures nothing
Mutable specifier (optional)
➔
Allows body to modify the parameters captured by copy, and to call their non-const member
functions. It means it can mutate (change its own state).
More information at: http://en.cppreference.com/w/cpp/language/lambda
One Definition Rule
Lambda functions 25 60/
More information at: http://en.cppreference.com/w/cpp/language/lambda
A lambda is created and saved in f1 and f2
Lambda Functions in action
(using std::function type in this example)
But f1 does not modify the x value despite being mutable.
f2 is not mutable but modifies x. Why?
f1 is mutable. x is passed by copy.
f2 is not mutable and is not allowed to change its state.
To f2, x is passed by reference.
f1 copies x and then changes it, within its own context.
f2 changes x because x is passed by reference.
f2 is not mutating its own state.
Structures and Classes 26 60/
More information at: http://en.cppreference.com/w/cpp/language/class
C++ provides two ways of structuring complex objects
Structures Classes
➔
By default, attributes and methods are
public (friendship)
➔ Can be used with C code
➔
By default, attributes and methods are
private (friendship)
➔ Cannot be used with C Code
In truth, these are the only differences between Structs and
Classes in C++.
Both Types support:
➔
Constructors
➔
Polymorphism through inheritance
➔
Friendship
➔
Operator Overloading
➔
Casts Operators
➔
They can even be mixed (classes
inheriting from structs and vice
versa)
➔
But classes are the standard for
oriented programming.
Structs and Classes Vocabulary→ 27 60/
More information at: http://en.cppreference.com/w/cpp/language/class
Vocabulary is important when talking about
Object Oriented Programming
Structs
Classes
Memory
Allocation Object
Object Instantiation
Object
Blueprints
Structs and Classes Breaking with the old→ 28 60/
Code organization is VERY important when talking
about Object Oriented Programming
Past Ghosts from C code organization
You were led to believe that:
➔
For each .hpp header, there should be a .cpp module.
➔
Header should only have prototypes, modules should have the real code.
Nothing could be further from the truth…
It is possible to develop C++ code using only headers, while having
only 1 module.
➔
Location where main is implemented.
➔
Location where static objects and class attributes are declared.
➔
Code in header files can be inlined!
Classes Attributes and Access Management→ 29 60/
By default, Class attributes are private
Enumeration can be defined within classes
static attribute. These are shared between all Top instantiations.
Private method. Can only be called from Top context or Top
friends (friendship explained later).
Private default constructor. There can be no Top X()
Protected attributes. A class that inherits from Top, can access
these attributes/methods.
private
public
private
protected
public
Public attributes. These can be accessed by everyone and
everything.
Be careful with these, if not const. State can be modified without
the object knowing about such.
Rule of Thumb! Object attributes should always be private, with the
exception of const attributes.
Classes Constructors and Destructor→ 30 60/
Result
Private unique pointer to string with
pointer default initialization
Copy Constructor
Move Constructor
Destructor
Default Constructor
Explicit String Copy Constructor
Acessing unique pointer
after move
Undefined Behaviour!
More information at: http://en.cppreference.com/w/cpp/language/classes
Classes Implicit Copy Constructor→ 31 60/
Implicit construction
Implicit constructors can be a source of
confusion.
B as a copy constructor for A
C as a copy constructor for B
C can be built using an object A using B
copy constructor as an intermediate.
C++ only travels 1 hop!
➔
C calls B calls A → Allowed!
➔
D calls C calls B calls A → Not Allowed!
Avoid the implicit construct by
marking a copy/type constructor
as explicit
Classes → const Methods and Attributes 32 60/
Result
const attribute. Once initialized, it cannot be
modified (immutable).
A const attribute can only be returned using a const
modifier with the returned value.
const modifier should be used when returning the
reference of an internal attribute.
const modifier for the method means, the method does
not modify the objet internal state
Never ever do this. It
exposes to modification, the
private attribute.
Moving a string.
string_moved
was cleared.
Classes Operator Overloading→ 33 60/
Result
Array subscript operator to access a specific
character from attr.
Sum operator to concatenate the attr from
two different Top objects.
Assignment operator to assign a new value to
attr coming from another Top object.
Stream insertion operator
➔ friend operator
➔ NOT a Top class operator!
➔
It is an Out-of-Member Operator
➔
No this reference access
Classes Casting Operators→ 34 60/
Cast Operators
➔
It allows an object to transformed
to other types of objects.
➔
By default, casts are implicit!
➔
Like the constructors, casts can be
declared explicit.
Result
Explicit cast
Implicit cast
Classes Inheritance & Polymorphism→ 35 60/
Polymorphism a fundamental concept in C++
It is divided into two different types
Run-time Polymorphism
➔ Implements a virtual table
(v-table) to provide
polymorphism.
➔
Overhead due to v-table.
➔
Requires Run Time Type
Information (RTTI)
Compile-Time Polymorphism
➔ Methods are not overridden
➔
No v-table
➔
No overhead
➔
No dynamic casting
➔
Good for code reuse
Disclaimer
I will not talk about Multiple-Inheritance
It is a complex world...
Classes Polymorphic Inheritance→ 36 60/
Abstract Class
➔
Classes with a pure virtual
method (= 0)
Pure Virtual
Methods must be
implemented by
lower classes.
Circle and Square
inherit from Figure
➔
In order for a method to be overridden, it needs to be declared as virtual.
➔
A polymorphic object is an object with at least one virtual method.
Polymorphic
objects must have
a virtual destructor
Classes Polymorphic Inheritance→ 37 60/
Result
Polymorphism allows a programmer to deal
with the abstract.
➔
A Figure list (Figure is the abstraction)
➔
Circle and Square are Figure implementations
The Virtual Table
➔
Calls are made to Circle and Square
implementations, respectively
➔
The virtual table pointer is located in memory,
along with the Information Type about the
Polymorphic class (extra 8 bytes in x86_64).
Classes Non-Polymorphic Inheritance→ 38 60/
Person_Name and Dog_Name
inherit from Name
There are no Virtual
members/constructs
Classes Non-Polymorphic Inheritance→ 39 60/
Result
No Polymorphism
➔
Methods are not
overridden
➔
There is no V-Table
Classes Friendship→ 40 60/
Friendship
➔
It allows an object to grant
access to specific entities
➔ Entities can be:
➢
Objects
➢
Methods
➔
Friend declaration can be
used for prototype.
➔
Beware! Objects internal
state can be exposed if
misused.
Casting in C++ 41 60/
C++ provides 4 types of Casting
Static Casting Dynamic Casting
Reinterpret Casting Const Casting
➔
Explicit casting
➔
Non-Polymorphic Casting
➔
Type checks are performed during compile-time
➔
Checks if conversion is possible
➔
Less restrictive than Dynamic Casting
➔
Used for Polymorphic Casting
➔
Performed during run-time
➔
The safest type of casting (and most expensive)
➔
The NUCLEAR CAST
➔
Direct conversion, just like C Casts
➔
Performs absolutely no type checks
➔
Can generate SegFaults if misused..
➔
Used to add or remove const attribute.
➔
Used when it is absolutely necessary to remove
consteness (anti-patern)
●
Buggy libraries where it is necessary to
break through const to solve issues.
●
Modifying const values results in undefined
behaviour.
More information at: http://en.cppreference.com/w/cpp/language/expressions#Conversions
42 60/
Lets take a break!
Questions?
3rd Part 43 60/
C++14
Increasing the complexity...
For every complex problem,
there is an answer that is
clear, simple, and wrong.
– H. L. Mencken
Exceptions 44 60/
Exceptions is how C++ deals with errors
Using exceptions allows to:
➔
Errors handling organization.
➔
Delegate error treatment to upper
calls, via stack unrolling.
All exceptions specification should
inherit from std::exception and
override the
const char * what() method.
Smart Pointers – Auto Memory Management 45 60/
Available at <memory>
More information at: http://en.cppreference.com/w/cpp/memory
Three types of Smart Pointers exist
Before C++11, there was only two choices:
➔
Manual Memory Management
●
Prone to errors and object leaks
●
Segfault Hell world...
➔
Resort to Boost Libraries
●
Despite high quality, not standard...
Unique Pointers
➔
Single Ownership
Shared Pointers
➔
Shared Ownership
Weak Pointers
➔
No Ownership
unique_ptr shared_ptr
weak_ptr
Smart pointers are responsible for the memory
management of the object to which they point!
After C++11, there are Smart Pointers!
➔
Automatic Memory Management
➔
Developer is free from memory management
●
Less bugs from object leaks
●
Objects existence is self managed
●
Increased Code robustness
Smart Pointers Unique Pointers→ 46 60/
More information at: http://en.cppreference.com/w/cpp/memory/unique_ptr
Unique pointers cannot be copied!
1 to 1 relationship with object
Result
Pointer is created with object constructor
arguments
Context is closed, pointer and object are
destroyed
Pointer is created, with object.
Pointer is transferred to Method
Method execution ends, pointer and object
are destroyed.
Unique pointers cost ZERO in
performance!
Smart Pointers Shared Pointers→ 47 60/
More information at: http://en.cppreference.com/w/cpp/memory/shared_ptr
Result
Pointer 1 is created without object
Pointer 2 is created with object
Pointer 2 is copied to pointer 1, reference
counter is increased in 1.
Context is closed, pointer 2 is destroyed
Context is closed, pointer 1 and object are
destroyed.
Shared pointers can be copied!
Many to 1 relationship with object
➔
Shared pointers track object ownership,
using a per-object, shared, internal
reference counter.
➔
When the counter reaches zero, the
object is destroyed.
Beware!
Shared pointers are vulnerable to
circular reference issues
Smart Pointers Weak Pointers→ 48 60/
More information at: http://en.cppreference.com/w/cpp/memory/weak_ptr
Weak pointer is created
Shared pointer 1 is created with object
Shared pointer 1 info related to object is
copied into weak pointer.
Verification if object still exists (true)
Shared pointer 2 is created from Weak
pointer.
Context is closed, pointer 2 is destroyed
Context is closed, pointer 1 and object are
destroyed
Verification if object no longer exists (true)
Weak pointers have no object ownership!
Used to avoid circular reference issues.
➔
To access an object pointed by weak
pointers, it is required to create a Shared
Pointer.
➔
Shared pointer creation may fail, if object
no longer exists!
Result
C++ Generic Containers→ 49 60/
The power of the Standard Template
Library, is easily seen in its Generic Data
containers.
Generic Containers (some of them)
➔
Arrays <array>
➔ Vectors <vector>
➔ Lists <list>
➔
Maps <map>
➔
Sets <set>
➔
Stacks <stack>
➔
Queues <queue>
More information at: http://en.cppreference.com/w/cpp/container
C++ Generic Algorithms→ 50 60/
Generic Algorithms for Generic
Structures.
➔ Searching
●
Binary Search
➔ Sorting
➔
Swapping
➔
Copying
➔
Partitioning
➔
Set Operations
➔
Minimum/Maximum Operations
➔
Numeric Operations
More information at: http://en.cppreference.com/w/cpp/algorithm
Result
Available at <algorithm>
C++ Threads and Locks→ 51 60/
More information at: http://en.cppreference.com/w/cpp/thread/thread
http://en.cppreference.com/w/cpp/thread/mutex
➔ Type declaration for the thread “main”
➔ Number of available hardware threads
➔
Shared counter
➔
List of Threads
➔ Threads will increase the counter, until it
reaches 1000000
➔ Thread object creation
➔
Moving thread to the list, NOT COPY!
➔ Master thread will wait for working
threads to end
➔
Final counter value is printed
Available at <thread>
C++ Threads and Locks→ 52 60/
Result
Result
More information at: http://en.cppreference.com/w/cpp/thread/thread
http://en.cppreference.com/w/cpp/thread/mutex
But… there is a synchronization problem!
For 90% of the trials, the result is
correct!
But the problem is the remaining
10%...
C++ Threads and Locks→ 53 60/
We solve the problem with a mutex!
Before accessing the shared
resource, the thread locks the access
When it no longer needs the
resource, it releases the lock!
Result
Available at <mutex>
4th Part 54 60/
C++14
Extreme Properties
It ain’t what you don’t know that gets you into trouble.
It’s what you know for sure that just ain’t so.
– Mark Twain
WARNING
If you don’t understand at first, don’t worry… neither did I
This is mostly to show C++14 capabilities
C++ Templates & SFINAE→ 55 60/
C++ provides a Meta-programming language
➔
It is very helpful for automatic code generation!
This language is implemented using templates
➔ The base of STL
➔ Allow the creation of Generic Code
➔
Developers focus on algorithms and establish boundaries
for type deduction
Substitution Failure Is Not An Error (SFINAE)
➔
This rule applies during overloading resolution of
function templates.
➔
Specializations are discarded, when the compiler fails to
substitute the types in the template parameters.
More information at: http://en.cppreference.com/w/cpp/language/templates
http://en.cppreference.com/w/cpp/language/partial_specialization
http://en.cppreference.com/w/cpp/language/sfinae
Template Processing
1st
➔
Recursive template code
evaluation
➔
Template Parameter Substitution
●
SFINAE validation
2nd
➔ Code Inlining and Compilation
C++ Automatic Type Deduction→ 56 60/
Result
➔ Just a “magic method” that outputs the name of the
object type
Template with automatic type deduction, with type identification from operation.
SFINAE rule discards incorrect template
Automatic type deduction from provided
value
Automatic type deduction from make_shared operation
More information at: http://en.cppreference.com/w/cpp/language/auto
C++ Templates with Type Traits→ 57 60/
Result
More information at: http://en.cppreference.com/w/cpp/header/type_traits
Templates with
Type Traits
Recursive
Templates
Available at <type_traits>
C++14 Efficient Modern Development→ 58 60/
Summarizing important C++ modern features
➔
Cleaner and Sane Syntax
➔
Lambda Functions
● Powerful way to organize code and reduce namespace pollution.
➔
Move Constructor and Move Semantics
●
Allows zero-copy transfer of attribute information
➔
Smart Pointers
●
Automatic Memory Management with Ownership Management
➔
Improved Generic Containers
●
Updated with Move semantics
➔
Improved Generic Algorithms
●
Lots of generic algorithms
●
C++17 will bring Parallel Algorithms
➔
Automatic Type Deduction
➔
Templates Type Traits
●
Type boundary capabilities
C++14 Resources→ 59 60/
Websites
➔
http://www.cppreference.com
➔
http://www.cplusplus.com/
Recommended Books
➔
The C++ Programming Language 4th Edition (Addison.Wesley Jun 2013)
➔
Programming Principles and Practice Using C++, 2nd Edition (Addison Wesley, 2014)
➔ Professional C++ 3rd Edition (2014)
➔ Effective Modern C++ (OReilly2014)
➔ C++ For Dummies, 7th Edition (2014)
➔
A Tour of C++ (2013 Addison Wesley)
Libraries and Frameworks worth of checking out
➔
Boost
➔
POCO
➔
QT5
C++14 We are done!→ 60 60/
Thank you for your patience!

More Related Content

What's hot

XPDS16: Porting Xen on ARM to a new SOC - Julien Grall, ARM
XPDS16: Porting Xen on ARM to a new SOC - Julien Grall, ARMXPDS16: Porting Xen on ARM to a new SOC - Julien Grall, ARM
XPDS16: Porting Xen on ARM to a new SOC - Julien Grall, ARM
The Linux Foundation
 
Improve Android System Component Performance
Improve Android System Component PerformanceImprove Android System Component Performance
Improve Android System Component Performance
National Cheng Kung University
 
OpenHPC: A Comprehensive System Software Stack
OpenHPC: A Comprehensive System Software StackOpenHPC: A Comprehensive System Software Stack
OpenHPC: A Comprehensive System Software Stack
inside-BigData.com
 
Bootstrap process of u boot (NDS32 RISC CPU)
Bootstrap process of u boot (NDS32 RISC CPU)Bootstrap process of u boot (NDS32 RISC CPU)
Bootstrap process of u boot (NDS32 RISC CPU)
Macpaul Lin
 
XPDDS18: CPUFreq in Xen on ARM - Oleksandr Tyshchenko, EPAM Systems
XPDDS18: CPUFreq in Xen on ARM - Oleksandr Tyshchenko, EPAM SystemsXPDDS18: CPUFreq in Xen on ARM - Oleksandr Tyshchenko, EPAM Systems
XPDDS18: CPUFreq in Xen on ARM - Oleksandr Tyshchenko, EPAM Systems
The Linux Foundation
 
SFO15-TR9: PSCI, ACPI (and UEFI to boot)
SFO15-TR9: PSCI, ACPI (and UEFI to boot)SFO15-TR9: PSCI, ACPI (and UEFI to boot)
SFO15-TR9: PSCI, ACPI (and UEFI to boot)
Linaro
 
Sisteme de Operare: Analiza executabilelor și proceselor
Sisteme de Operare: Analiza executabilelor și proceselorSisteme de Operare: Analiza executabilelor și proceselor
Sisteme de Operare: Analiza executabilelor și proceselor
Alexandru Radovici
 
その文字列検索、std::string::findだけで大丈夫ですか?【Sapporo.cpp 第8回勉強会(2014.12.27)】
その文字列検索、std::string::findだけで大丈夫ですか?【Sapporo.cpp 第8回勉強会(2014.12.27)】その文字列検索、std::string::findだけで大丈夫ですか?【Sapporo.cpp 第8回勉強会(2014.12.27)】
その文字列検索、std::string::findだけで大丈夫ですか?【Sapporo.cpp 第8回勉強会(2014.12.27)】
Hiro H.
 
from Binary to Binary: How Qemu Works
from Binary to Binary: How Qemu Worksfrom Binary to Binary: How Qemu Works
from Binary to Binary: How Qemu Works
Zhen Wei
 
WaTZ: A Trusted WebAssembly Runtime Environment with Remote Attestation for T...
WaTZ: A Trusted WebAssembly Runtime Environment with Remote Attestation for T...WaTZ: A Trusted WebAssembly Runtime Environment with Remote Attestation for T...
WaTZ: A Trusted WebAssembly Runtime Environment with Remote Attestation for T...
Jämes Ménétrey
 
Embedded_Linux_Booting
Embedded_Linux_BootingEmbedded_Linux_Booting
Embedded_Linux_BootingRashila Rr
 
CISC e RISC
CISC e RISCCISC e RISC
CISC e RISC
Bibina_Karen
 
Misra c-2004
Misra c-2004Misra c-2004
Misra c-2004sand390
 
Qemu JIT Code Generator and System Emulation
Qemu JIT Code Generator and System EmulationQemu JIT Code Generator and System Emulation
Qemu JIT Code Generator and System Emulation
National Cheng Kung University
 
U Boot or Universal Bootloader
U Boot or Universal BootloaderU Boot or Universal Bootloader
U Boot or Universal Bootloader
Satpal Parmar
 
Virtualization Support in ARMv8+
Virtualization Support in ARMv8+Virtualization Support in ARMv8+
Virtualization Support in ARMv8+
Aananth C N
 
oSC22ww4.pdf
oSC22ww4.pdfoSC22ww4.pdf
oSC22ww4.pdf
ChristianGoll1
 
Android Logging System
Android Logging SystemAndroid Logging System
Android Logging System
William Lee
 

What's hot (20)

Qemu
QemuQemu
Qemu
 
XPDS16: Porting Xen on ARM to a new SOC - Julien Grall, ARM
XPDS16: Porting Xen on ARM to a new SOC - Julien Grall, ARMXPDS16: Porting Xen on ARM to a new SOC - Julien Grall, ARM
XPDS16: Porting Xen on ARM to a new SOC - Julien Grall, ARM
 
Improve Android System Component Performance
Improve Android System Component PerformanceImprove Android System Component Performance
Improve Android System Component Performance
 
OpenHPC: A Comprehensive System Software Stack
OpenHPC: A Comprehensive System Software StackOpenHPC: A Comprehensive System Software Stack
OpenHPC: A Comprehensive System Software Stack
 
Bootstrap process of u boot (NDS32 RISC CPU)
Bootstrap process of u boot (NDS32 RISC CPU)Bootstrap process of u boot (NDS32 RISC CPU)
Bootstrap process of u boot (NDS32 RISC CPU)
 
XPDDS18: CPUFreq in Xen on ARM - Oleksandr Tyshchenko, EPAM Systems
XPDDS18: CPUFreq in Xen on ARM - Oleksandr Tyshchenko, EPAM SystemsXPDDS18: CPUFreq in Xen on ARM - Oleksandr Tyshchenko, EPAM Systems
XPDDS18: CPUFreq in Xen on ARM - Oleksandr Tyshchenko, EPAM Systems
 
SFO15-TR9: PSCI, ACPI (and UEFI to boot)
SFO15-TR9: PSCI, ACPI (and UEFI to boot)SFO15-TR9: PSCI, ACPI (and UEFI to boot)
SFO15-TR9: PSCI, ACPI (and UEFI to boot)
 
Linux training
Linux trainingLinux training
Linux training
 
Sisteme de Operare: Analiza executabilelor și proceselor
Sisteme de Operare: Analiza executabilelor și proceselorSisteme de Operare: Analiza executabilelor și proceselor
Sisteme de Operare: Analiza executabilelor și proceselor
 
その文字列検索、std::string::findだけで大丈夫ですか?【Sapporo.cpp 第8回勉強会(2014.12.27)】
その文字列検索、std::string::findだけで大丈夫ですか?【Sapporo.cpp 第8回勉強会(2014.12.27)】その文字列検索、std::string::findだけで大丈夫ですか?【Sapporo.cpp 第8回勉強会(2014.12.27)】
その文字列検索、std::string::findだけで大丈夫ですか?【Sapporo.cpp 第8回勉強会(2014.12.27)】
 
from Binary to Binary: How Qemu Works
from Binary to Binary: How Qemu Worksfrom Binary to Binary: How Qemu Works
from Binary to Binary: How Qemu Works
 
WaTZ: A Trusted WebAssembly Runtime Environment with Remote Attestation for T...
WaTZ: A Trusted WebAssembly Runtime Environment with Remote Attestation for T...WaTZ: A Trusted WebAssembly Runtime Environment with Remote Attestation for T...
WaTZ: A Trusted WebAssembly Runtime Environment with Remote Attestation for T...
 
Embedded_Linux_Booting
Embedded_Linux_BootingEmbedded_Linux_Booting
Embedded_Linux_Booting
 
CISC e RISC
CISC e RISCCISC e RISC
CISC e RISC
 
Misra c-2004
Misra c-2004Misra c-2004
Misra c-2004
 
Qemu JIT Code Generator and System Emulation
Qemu JIT Code Generator and System EmulationQemu JIT Code Generator and System Emulation
Qemu JIT Code Generator and System Emulation
 
U Boot or Universal Bootloader
U Boot or Universal BootloaderU Boot or Universal Bootloader
U Boot or Universal Bootloader
 
Virtualization Support in ARMv8+
Virtualization Support in ARMv8+Virtualization Support in ARMv8+
Virtualization Support in ARMv8+
 
oSC22ww4.pdf
oSC22ww4.pdfoSC22ww4.pdf
oSC22ww4.pdf
 
Android Logging System
Android Logging SystemAndroid Logging System
Android Logging System
 

Viewers also liked

Physique-Pro-Gym-Services-to-Public
Physique-Pro-Gym-Services-to-PublicPhysique-Pro-Gym-Services-to-Public
Physique-Pro-Gym-Services-to-PublicEfrem Martin
 
Proyecto # 1
Proyecto # 1Proyecto # 1
Proyecto # 1
jeankrs9
 
LIFE HACK: How To Make The Most Of Your Time Off
LIFE HACK: How To Make The Most Of Your Time OffLIFE HACK: How To Make The Most Of Your Time Off
LIFE HACK: How To Make The Most Of Your Time Off
The Change School
 
Cv 03 16
Cv 03 16Cv 03 16
Cv 16 06(1)
Cv 16 06(1)Cv 16 06(1)
Cv 16 06(1)
parohiavaleamare
 
Storyboard as media film opening
Storyboard as media film openingStoryboard as media film opening
Storyboard as media film opening
christoph24898
 
Ebola
Ebola Ebola
Luisiana 200 años versión español
Luisiana 200 años versión españolLuisiana 200 años versión español
Luisiana 200 años versión español
nube974
 
What every C++ programmer should know about modern compilers (w/o comments, A...
What every C++ programmer should know about modern compilers (w/o comments, A...What every C++ programmer should know about modern compilers (w/o comments, A...
What every C++ programmer should know about modern compilers (w/o comments, A...
Sławomir Zborowski
 
Las Redes Sociales
Las Redes SocialesLas Redes Sociales
Las Redes Sociales
asierra447
 
КП RT-Voice
КП RT-VoiceКП RT-Voice
КП RT-Voice
ifranz74
 
"Финансовый лизинг в МСФО и РСБУ. Методика расчета и отражение в учете"
"Финансовый лизинг в МСФО и РСБУ. Методика расчета и отражение в учете""Финансовый лизинг в МСФО и РСБУ. Методика расчета и отражение в учете"
"Финансовый лизинг в МСФО и РСБУ. Методика расчета и отражение в учете"
Елена Коптева
 
Презентация "Scrum с нуля" (2 часть)
Презентация "Scrum с нуля" (2 часть)Презентация "Scrum с нуля" (2 часть)
Презентация "Scrum с нуля" (2 часть)
Елена Коптева
 

Viewers also liked (13)

Physique-Pro-Gym-Services-to-Public
Physique-Pro-Gym-Services-to-PublicPhysique-Pro-Gym-Services-to-Public
Physique-Pro-Gym-Services-to-Public
 
Proyecto # 1
Proyecto # 1Proyecto # 1
Proyecto # 1
 
LIFE HACK: How To Make The Most Of Your Time Off
LIFE HACK: How To Make The Most Of Your Time OffLIFE HACK: How To Make The Most Of Your Time Off
LIFE HACK: How To Make The Most Of Your Time Off
 
Cv 03 16
Cv 03 16Cv 03 16
Cv 03 16
 
Cv 16 06(1)
Cv 16 06(1)Cv 16 06(1)
Cv 16 06(1)
 
Storyboard as media film opening
Storyboard as media film openingStoryboard as media film opening
Storyboard as media film opening
 
Ebola
Ebola Ebola
Ebola
 
Luisiana 200 años versión español
Luisiana 200 años versión españolLuisiana 200 años versión español
Luisiana 200 años versión español
 
What every C++ programmer should know about modern compilers (w/o comments, A...
What every C++ programmer should know about modern compilers (w/o comments, A...What every C++ programmer should know about modern compilers (w/o comments, A...
What every C++ programmer should know about modern compilers (w/o comments, A...
 
Las Redes Sociales
Las Redes SocialesLas Redes Sociales
Las Redes Sociales
 
КП RT-Voice
КП RT-VoiceКП RT-Voice
КП RT-Voice
 
"Финансовый лизинг в МСФО и РСБУ. Методика расчета и отражение в учете"
"Финансовый лизинг в МСФО и РСБУ. Методика расчета и отражение в учете""Финансовый лизинг в МСФО и РСБУ. Методика расчета и отражение в учете"
"Финансовый лизинг в МСФО и РСБУ. Методика расчета и отражение в учете"
 
Презентация "Scrum с нуля" (2 часть)
Презентация "Scrum с нуля" (2 часть)Презентация "Scrum с нуля" (2 часть)
Презентация "Scrum с нуля" (2 часть)
 

Similar to C++14 - Modern Programming for Demanding Times

Introduction-to-C-Part-1.pdf
Introduction-to-C-Part-1.pdfIntroduction-to-C-Part-1.pdf
Introduction-to-C-Part-1.pdf
AnassElHousni
 
Object Oriented Programming using C++ - Part 1
Object Oriented Programming using C++ - Part 1Object Oriented Programming using C++ - Part 1
Object Oriented Programming using C++ - Part 1
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
C++Basics2022.pptx
C++Basics2022.pptxC++Basics2022.pptx
C++Basics2022.pptx
Danielle780357
 
Introduction-to-C-Part-1 (1).doc
Introduction-to-C-Part-1 (1).docIntroduction-to-C-Part-1 (1).doc
Introduction-to-C-Part-1 (1).doc
MayurWagh46
 
Introduction-to-C-Part-1.pptx
Introduction-to-C-Part-1.pptxIntroduction-to-C-Part-1.pptx
Introduction-to-C-Part-1.pptx
NEHARAJPUT239591
 
Introduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJ
Introduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJIntroduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJ
Introduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJ
meharikiros2
 
C++ helps you to format the I/O operations like determining the number of dig...
C++ helps you to format the I/O operations like determining the number of dig...C++ helps you to format the I/O operations like determining the number of dig...
C++ helps you to format the I/O operations like determining the number of dig...
bhargavi804095
 
C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...
C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...
C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...
bhargavi804095
 
c programming L-1.pdf43333333544444444444444444444
c programming L-1.pdf43333333544444444444444444444c programming L-1.pdf43333333544444444444444444444
c programming L-1.pdf43333333544444444444444444444
PurvaShyama
 
Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016
maiktoepfer
 
Stroustrup c++0x overview
Stroustrup c++0x overviewStroustrup c++0x overview
Stroustrup c++0x overviewVaibhav Bajaj
 
Keep your repo clean
Keep your repo cleanKeep your repo clean
Keep your repo clean
Hector Canto
 
C++primer
C++primerC++primer
C++primer
leonlongli
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
Sangharsh agarwal
 
Introduction to c++ ppt 1
Introduction to c++ ppt 1Introduction to c++ ppt 1
Introduction to c++ ppt 1
Prof. Dr. K. Adisesha
 
If I Had a Hammer...
If I Had a Hammer...If I Had a Hammer...
If I Had a Hammer...
Kevlin Henney
 
Return of c++
Return of c++Return of c++
Return of c++
Yongwei Wu
 

Similar to C++14 - Modern Programming for Demanding Times (20)

11 cpp
11 cpp11 cpp
11 cpp
 
Introduction-to-C-Part-1.pdf
Introduction-to-C-Part-1.pdfIntroduction-to-C-Part-1.pdf
Introduction-to-C-Part-1.pdf
 
Object Oriented Programming using C++ - Part 1
Object Oriented Programming using C++ - Part 1Object Oriented Programming using C++ - Part 1
Object Oriented Programming using C++ - Part 1
 
C++Basics2022.pptx
C++Basics2022.pptxC++Basics2022.pptx
C++Basics2022.pptx
 
Introduction-to-C-Part-1 (1).doc
Introduction-to-C-Part-1 (1).docIntroduction-to-C-Part-1 (1).doc
Introduction-to-C-Part-1 (1).doc
 
Introduction-to-C-Part-1.pptx
Introduction-to-C-Part-1.pptxIntroduction-to-C-Part-1.pptx
Introduction-to-C-Part-1.pptx
 
Introduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJ
Introduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJIntroduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJ
Introduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJ
 
C_Programming_Notes_ICE
C_Programming_Notes_ICEC_Programming_Notes_ICE
C_Programming_Notes_ICE
 
C++ helps you to format the I/O operations like determining the number of dig...
C++ helps you to format the I/O operations like determining the number of dig...C++ helps you to format the I/O operations like determining the number of dig...
C++ helps you to format the I/O operations like determining the number of dig...
 
College1
College1College1
College1
 
C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...
C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...
C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...
 
c programming L-1.pdf43333333544444444444444444444
c programming L-1.pdf43333333544444444444444444444c programming L-1.pdf43333333544444444444444444444
c programming L-1.pdf43333333544444444444444444444
 
Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016
 
Stroustrup c++0x overview
Stroustrup c++0x overviewStroustrup c++0x overview
Stroustrup c++0x overview
 
Keep your repo clean
Keep your repo cleanKeep your repo clean
Keep your repo clean
 
C++primer
C++primerC++primer
C++primer
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
Introduction to c++ ppt 1
Introduction to c++ ppt 1Introduction to c++ ppt 1
Introduction to c++ ppt 1
 
If I Had a Hammer...
If I Had a Hammer...If I Had a Hammer...
If I Had a Hammer...
 
Return of c++
Return of c++Return of c++
Return of c++
 

Recently uploaded

OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
Sharepoint Designs
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
KrzysztofKkol1
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
ayushiqss
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
Jelle | Nordend
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 

Recently uploaded (20)

OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 

C++14 - Modern Programming for Demanding Times

  • 1. NAP Talks C++14: Modern Programming for Demanding Times Speaker: Carlos Miguel Ferreira Position: PhD Student and IT Researcher Contact: carlosmf.pt@gmail.com
  • 2. Layout 1st Part – Some History ➔ Some background about C++ ➔ Philosophy ➔ The International Standard ➔ Boost ➔ Standard Template Library Break Time 2 60/ 2nd Part – The Basics ➔ Standard Types ➔ Methods ➔ Pointers and References ➔ Lambda Functions ➔ Casting in C++ ➔ Structures and Classes 4th Part - Extreme C++ ➔ Automatic Type Deduction ➔ Templates & Meta-Programming ➔ SFINAE rule ➔ Type Traits 3rd Part – Increased complexity ➔ Exceptions ➔ Smart Pointers ➔ Generic Containers ➔ Generic Algorithms ➔ Multi-threading ➔ Synchronization
  • 3. 1st Part 3 60/ C++14 History, Philosophy and Standards Why waste time learning when ignorance is instantaneous? – Hobbes
  • 4. C++ History 4 60/ The author: Bjarne Stroustrup Development starts by the around 1978, during his PhD at Churchill College, Cambridge. Took inspiration from Simula ➔ Known as the first language to support Object Oriented Programming. ➔ But it was to slow for practical use... In the beginning, It was called “C with Classes” First compiler: Cfront (derived from Cpre) ➔ Under the hood, just a translator ● Translating classes to pure C. ● Self-hosting compiler ● Supported classes, basic inheritance, inlining, default arguments ● It did not officially supported the OO paradigm...
  • 5. C++ History 5 60/ In 1983: ➔ The language changes the name to C++ ➔ First implementation in use In 1986: ➔ First commercial release (Cfront PC port) ➔ But still no available standard… In 1987: ➔ GNU C++ compiler v0.9 beta is released by Richard Stallman. ➔ New features were added: ● Virtual functions, overloading, references… ● It could then be called an Object Oriented Programming Language! ● “The C++ Programming Language 1st Ed.” book is released. Free Software Foundation Founder
  • 6. C++ Philosophy 6 60/ Some of the philosophical rules that guide the C++ language development. Not All! Know more from the paper “Evolving a language in and for the real world: C++ 1991-2006” DOI: 10.1145/1238844.1238848 General ➔ C++ evolution must be driven by real problems. ➔ Every feature must have a reasonably obvious implementation. ➔ C++ is a language, not a complete system. ➔ Don’t try to force people to use a specific programming style. Technical ➔ Locality is good. ➔ Avoid order dependencies. ➔ Preprocessor usage should be eliminated. Low-Level Support ➔ Leave no room for a lower-level language below C++ (except assembler). ➔ What you don’t use, you don’t pay for (zero- overhead rule). Design ➔ Say what you mean. ➔ Provide facilities for program organization. ➔ All features must be affordable.
  • 7. C++ International Standards (ISO) 7 60/ What are Technical Standards? Even better, what are International Standards? Technical Standards A technical standard is an established norm or requirement in regard to technical systems. It is usually a formal document that establishes uniform engineering or technical criteria, methods, processes and practices. In contrast, a custom, convention, company product, corporate standard, etc. that becomes generally accepted and dominant is often called a de facto standard. International Standards International standards are one way of overcoming technical barriers in international commerce caused by differences among technical regulations and standards developed independently and separately by each nation, national standards organization, or company. Technical barriers arise when different groups come together, each with a large user base, doing some well established thing that between them is mutually incompatible. Establishing international standards is one way of preventing or overcoming this problem. According to Wikipedia...
  • 8. C++ International Standards (ISO) 8 60/ The C++ Standard intends to: ➔ Create an abstraction of a general computing machine. ➔ Defines a very rigid technical specification, asserting code portability. ● It Defines Behaviours, and more important Undefined Behaviours! ➔ Defines the Standard Library (std::) behaviour. Very Important! ● You will see lots of "the behaviour is defined/undefined" indications, in the C++ reference manuals. ➔ It gave us the Standard Template Library (STL) The C++ Standard is maintained by a Committee: ➔ Composed by companies, academics and freelancers representatives. ➔ Very strict review of new additions to the standard. ➔ Promote C++ learning and adoption. ➔ They usually take some time… ● First Commercial was release in 1987... ● But the 1st ISO only came out in 1998! (C++98: ISO/IEC 14882:1998)
  • 9. C++ International Standards (ISO) 9 60/ C++98 ➔ The first one ➔ 1998 ➔ ISO/IEC 14882:1998 ➔ Single Threading by design. C++03 ➔ 2003 ➔ ISO/IEC 14882:2003 Existing C++ Standards C++11 ➔ 2011 ➔ ISO/IEC 14882:2011 ➔ Multi-threaded by design C++14 ➔ 2014 ➔ ISO/IEC 14882:2014 C++17 ➔ Expected 2017 Old and quirky New and Improved! vector<vector<int> > vector_of_int_vectors; The lack of a space between the “> >” was an error in C++03. The compiler got confused with the “>>” operator. More information at: https://isocpp.org/std/status
  • 10. C++ Boost→ 10 60/ “Boost provides free peer-reviewed portable C++ source libraries. We emphasize libraries that work well with the C++ Standard Library. Boost libraries are intended to be widely useful, and usable across a broad spectrum of applications. The Boost license encourages both commercial and non-commercial use. We aim to establish "existing practice" and provide reference implementations so that Boost libraries are suitable for eventual standardization. Ten Boost libraries are included in the C++ Standards Committee's Library Technical Report (TR1) and in the new C++11 Standard. C++11 also includes several more Boost libraries in addition to those from TR1. More Boost libraries are proposed for standardization in C++17.” The Boost Libraries ➔ First release in 1998 ➔ After the Standard Library, Boost is the most important library available to the C++ development community. ➔ Many of its own libraries made their way to the C++11 standard! ● Arrays ● Regular Expressions ● Complex numbers ➔ More will be added to C++17. ● Filesystem More information at: https://www.boost.org
  • 11. C++ Standard Template Library→ 11 60/ What is the Standard Template Library (STL)? ➔ A set of Generalized Structures ➔ A set of Algorithms for Generalized Structures ● The key here is generalized. ● STL does not deal in specifics! ➔ Separates algorithms from storage in a way that is classical (as in math) but not object oriented. ➔ It separates policy decisions of algorithms, such as sorting and search criteria, from the container, and the element class. ➔ Standardized Structures and Behaviours! Some of the available containers <array> <list> <map> <queue> <set> <stack> <vector> and many others... More information at: http://en.cppreference.com/w/cpp/container Later, I will talk more about these containers The result? Unsurpassed flexibility and performance.
  • 12. C++ 14 12 60/ This talk is about the C++14 Standard. Threads Containers Lambda Expressions Automatic Type deduction Ranged for Loops Move Constructors Initialization Lists Type Traits Smart Pointers
  • 13. 2nd Part 13 60/ C++14 Lets start with the basics! A programmer is a machine for turning caffeine into code. – A programmer
  • 14. Including 14 60/ C++ has many new features not present in C To maintain compatibility and to keep C libraries usable in C++ environments, the standard provides compatibility header files: <cassert> (assert.h) → C Diagnostics Library <cctype> (ctype.h) → Character handling functions <cerrno> (errno.h) → C Errors <csignal> (signal.h) → C library to handle signals <cstdio> (stdio.h) → C library to perform Input/Output operations <cstdlib> (stdlib.h) → C Standard General Utilities Library <cstring> (string.h) → C Strings <ctgmath> (tgmath.h) → Type-generic math <ctime> (time.h) → C Time Library <cuchar> (uchar.h) → Unicode characters <cwchar> (wchar.h) → Wide characters <cwctype> (wctype.h) → Wide character The C precedes the name of the classical C header. More information at: http://en.cppreference.com/w/cpp/header
  • 15. The main function. 15 60/ Global method term used to catch unhandled exceptions. Uncaught exception handler is registered. Program arguments are caught and std::strings are created. Don’t worry about the Exception I will talk about them later... std::exception is throwed.
  • 16. Namespaces 16 60/ Same method declared in different namespaces. Result: Namespaces are great for code management! Explicitly choose the namespace Or specifically state your intentions The std:: namespace contains every C++ standardized type, function and object.
  • 17. Standard Types → void, bool and char 17 60/ The C++ 14 standard specifies the behaviour for a set of types. ➔ Most are from C99 standard. ➔ Fundamental types are not inside the namespace std:: Void type ➔ void ➔ nullptr literal ➔ std::nullptr_t type Boolean Type ➔ bool → true or false Character types ➔ char (signed/unsigned) ➔ wchar_t ➔ char16_t ➔ char32_t Special types! Standard dictactes there cannot be void type arrays. void size is undefined! The most efficiently processed character representation on the target system (size undefined). The necessary size to represent any kind of supported character code unit (32bits for Unicode systems). Large enough for: ● UTF-16 ● UTF-32 Size is 1 byte
  • 18. Standard Types i→ nteger, float and double 18 60/ Floating point types (IEEE-754)Integer types ➔ float → single precision ➔ double → double precision ➔ long double → extended precision int (signed/unsigned)→ 2 bytes at least ➔ short –----→ 2 bytes at least ➔ long –----→ 4 bytes at least ➔ long long –----→ 8 bytes at least More information at: http://en.cppreference.com/w/cpp/language/types Defined by Standard ➔ Sizes are undefined. ➔ Instead, the standard defines the precision behaviour, and special values. ● Infinity ● Negative Zero ● Not-a-Number (NaN) ➔ Arithmetic operations are also specified
  • 19. Standard Types Fixed Width Integers→ 19 60/ Fixed Width Integer types (all within std::) int8_t int16_t int32_t int64_t int_fast8_t int_fast16_t int_fast32_t int_fast64_t int_least8_t int_least16_t int_least32_t int_least64_t intmax_t intptr_t More information at: http://en.cppreference.com/w/cpp/types/integer uint8_t uint16_t uint32_t uint64_t uint_fast8_t uint_fast16_t uint_fast32_t uint_fast64_t uint_least8_t uint_least16_t uint_least32_t uint_least64_t uintmax_t uintptr_t ➢ Integer type with width of exactly 8, 16, 32 and 64 bits Signed Unsigned ➢ Fastest integer type with width of at least 8, 16, 32 and 64 bits ➢ Smallest integer type with width of at least 8, 16, 32 and 64 bits ➢ Maximum width integer type ➢ Integer type capable of holding a pointer
  • 20. Standard Types Enumerators→ 20 60/ Specifying the enum memory size ➔ This is a hidden inheritance Enumerations declarations ➔ By default, the size is int Get the defined enumerations using the :: scope resolution operator
  • 21. Standard Types Strings→ 21 60/ Available at <string> Regular expressions at <regex> ➔ String → char ➔ wstring → wchar_t ➔ u16string → char16_t ➔ u32string → char32_t More information at: http://en.cppreference.com/w/cpp/header/string These types use these fundamental types underneath Initializations Attributions Concatenations Iterations Compatibility
  • 22. Methods 22 60/ Result Method Overloading The names are equal ➔ Different signatures for equivalent behaviours ➔ Keep code clean, elegant! ➔ No method naming Hell!
  • 23. Pointers, References and the const specifier 23 60/ Pointers and References (prefer references, unless working with C) Pointers are useful but: ➔ Is there really an object at address 0x123? ➔ Good code always checks if memory is accessible. ➔ Memory checks cost processing time... ➔ A pointer value could be NULL References provide assurance: ➔ Object must exists! (sort of) The const type qualifier provides robustness: ➔ Forbids state modification Yes, you can always hack it, but seriously… don’t… ➔ Always avoid this ● Unless you’re using a buggy library… ➔ Never ever in your life do this!!! ● You have been warned! ● The segfault Hell awaits you, if you ignore...
  • 24. Lambda functions 24 60/ Also called anonymous functions Lambda functions are useful to: ➔ Keep code localized and contained ➔ Pass callbacks to functions, event managers or threads! Lambda signature ➔ [ capture-list ] ( params ) mutable → ret { body } Capture List ➔ [a,&b] → a captured by value and b is captured by reference. ➔ [&] → captures all automatic variables odr-used in the body of the lambda by reference ➔ [=] → captures all automatic variables odr-used in the body of the lambda by value ➔ [] → captures nothing Mutable specifier (optional) ➔ Allows body to modify the parameters captured by copy, and to call their non-const member functions. It means it can mutate (change its own state). More information at: http://en.cppreference.com/w/cpp/language/lambda One Definition Rule
  • 25. Lambda functions 25 60/ More information at: http://en.cppreference.com/w/cpp/language/lambda A lambda is created and saved in f1 and f2 Lambda Functions in action (using std::function type in this example) But f1 does not modify the x value despite being mutable. f2 is not mutable but modifies x. Why? f1 is mutable. x is passed by copy. f2 is not mutable and is not allowed to change its state. To f2, x is passed by reference. f1 copies x and then changes it, within its own context. f2 changes x because x is passed by reference. f2 is not mutating its own state.
  • 26. Structures and Classes 26 60/ More information at: http://en.cppreference.com/w/cpp/language/class C++ provides two ways of structuring complex objects Structures Classes ➔ By default, attributes and methods are public (friendship) ➔ Can be used with C code ➔ By default, attributes and methods are private (friendship) ➔ Cannot be used with C Code In truth, these are the only differences between Structs and Classes in C++. Both Types support: ➔ Constructors ➔ Polymorphism through inheritance ➔ Friendship ➔ Operator Overloading ➔ Casts Operators ➔ They can even be mixed (classes inheriting from structs and vice versa) ➔ But classes are the standard for oriented programming.
  • 27. Structs and Classes Vocabulary→ 27 60/ More information at: http://en.cppreference.com/w/cpp/language/class Vocabulary is important when talking about Object Oriented Programming Structs Classes Memory Allocation Object Object Instantiation Object Blueprints
  • 28. Structs and Classes Breaking with the old→ 28 60/ Code organization is VERY important when talking about Object Oriented Programming Past Ghosts from C code organization You were led to believe that: ➔ For each .hpp header, there should be a .cpp module. ➔ Header should only have prototypes, modules should have the real code. Nothing could be further from the truth… It is possible to develop C++ code using only headers, while having only 1 module. ➔ Location where main is implemented. ➔ Location where static objects and class attributes are declared. ➔ Code in header files can be inlined!
  • 29. Classes Attributes and Access Management→ 29 60/ By default, Class attributes are private Enumeration can be defined within classes static attribute. These are shared between all Top instantiations. Private method. Can only be called from Top context or Top friends (friendship explained later). Private default constructor. There can be no Top X() Protected attributes. A class that inherits from Top, can access these attributes/methods. private public private protected public Public attributes. These can be accessed by everyone and everything. Be careful with these, if not const. State can be modified without the object knowing about such. Rule of Thumb! Object attributes should always be private, with the exception of const attributes.
  • 30. Classes Constructors and Destructor→ 30 60/ Result Private unique pointer to string with pointer default initialization Copy Constructor Move Constructor Destructor Default Constructor Explicit String Copy Constructor Acessing unique pointer after move Undefined Behaviour! More information at: http://en.cppreference.com/w/cpp/language/classes
  • 31. Classes Implicit Copy Constructor→ 31 60/ Implicit construction Implicit constructors can be a source of confusion. B as a copy constructor for A C as a copy constructor for B C can be built using an object A using B copy constructor as an intermediate. C++ only travels 1 hop! ➔ C calls B calls A → Allowed! ➔ D calls C calls B calls A → Not Allowed! Avoid the implicit construct by marking a copy/type constructor as explicit
  • 32. Classes → const Methods and Attributes 32 60/ Result const attribute. Once initialized, it cannot be modified (immutable). A const attribute can only be returned using a const modifier with the returned value. const modifier should be used when returning the reference of an internal attribute. const modifier for the method means, the method does not modify the objet internal state Never ever do this. It exposes to modification, the private attribute. Moving a string. string_moved was cleared.
  • 33. Classes Operator Overloading→ 33 60/ Result Array subscript operator to access a specific character from attr. Sum operator to concatenate the attr from two different Top objects. Assignment operator to assign a new value to attr coming from another Top object. Stream insertion operator ➔ friend operator ➔ NOT a Top class operator! ➔ It is an Out-of-Member Operator ➔ No this reference access
  • 34. Classes Casting Operators→ 34 60/ Cast Operators ➔ It allows an object to transformed to other types of objects. ➔ By default, casts are implicit! ➔ Like the constructors, casts can be declared explicit. Result Explicit cast Implicit cast
  • 35. Classes Inheritance & Polymorphism→ 35 60/ Polymorphism a fundamental concept in C++ It is divided into two different types Run-time Polymorphism ➔ Implements a virtual table (v-table) to provide polymorphism. ➔ Overhead due to v-table. ➔ Requires Run Time Type Information (RTTI) Compile-Time Polymorphism ➔ Methods are not overridden ➔ No v-table ➔ No overhead ➔ No dynamic casting ➔ Good for code reuse Disclaimer I will not talk about Multiple-Inheritance It is a complex world...
  • 36. Classes Polymorphic Inheritance→ 36 60/ Abstract Class ➔ Classes with a pure virtual method (= 0) Pure Virtual Methods must be implemented by lower classes. Circle and Square inherit from Figure ➔ In order for a method to be overridden, it needs to be declared as virtual. ➔ A polymorphic object is an object with at least one virtual method. Polymorphic objects must have a virtual destructor
  • 37. Classes Polymorphic Inheritance→ 37 60/ Result Polymorphism allows a programmer to deal with the abstract. ➔ A Figure list (Figure is the abstraction) ➔ Circle and Square are Figure implementations The Virtual Table ➔ Calls are made to Circle and Square implementations, respectively ➔ The virtual table pointer is located in memory, along with the Information Type about the Polymorphic class (extra 8 bytes in x86_64).
  • 38. Classes Non-Polymorphic Inheritance→ 38 60/ Person_Name and Dog_Name inherit from Name There are no Virtual members/constructs
  • 39. Classes Non-Polymorphic Inheritance→ 39 60/ Result No Polymorphism ➔ Methods are not overridden ➔ There is no V-Table
  • 40. Classes Friendship→ 40 60/ Friendship ➔ It allows an object to grant access to specific entities ➔ Entities can be: ➢ Objects ➢ Methods ➔ Friend declaration can be used for prototype. ➔ Beware! Objects internal state can be exposed if misused.
  • 41. Casting in C++ 41 60/ C++ provides 4 types of Casting Static Casting Dynamic Casting Reinterpret Casting Const Casting ➔ Explicit casting ➔ Non-Polymorphic Casting ➔ Type checks are performed during compile-time ➔ Checks if conversion is possible ➔ Less restrictive than Dynamic Casting ➔ Used for Polymorphic Casting ➔ Performed during run-time ➔ The safest type of casting (and most expensive) ➔ The NUCLEAR CAST ➔ Direct conversion, just like C Casts ➔ Performs absolutely no type checks ➔ Can generate SegFaults if misused.. ➔ Used to add or remove const attribute. ➔ Used when it is absolutely necessary to remove consteness (anti-patern) ● Buggy libraries where it is necessary to break through const to solve issues. ● Modifying const values results in undefined behaviour. More information at: http://en.cppreference.com/w/cpp/language/expressions#Conversions
  • 42. 42 60/ Lets take a break! Questions?
  • 43. 3rd Part 43 60/ C++14 Increasing the complexity... For every complex problem, there is an answer that is clear, simple, and wrong. – H. L. Mencken
  • 44. Exceptions 44 60/ Exceptions is how C++ deals with errors Using exceptions allows to: ➔ Errors handling organization. ➔ Delegate error treatment to upper calls, via stack unrolling. All exceptions specification should inherit from std::exception and override the const char * what() method.
  • 45. Smart Pointers – Auto Memory Management 45 60/ Available at <memory> More information at: http://en.cppreference.com/w/cpp/memory Three types of Smart Pointers exist Before C++11, there was only two choices: ➔ Manual Memory Management ● Prone to errors and object leaks ● Segfault Hell world... ➔ Resort to Boost Libraries ● Despite high quality, not standard... Unique Pointers ➔ Single Ownership Shared Pointers ➔ Shared Ownership Weak Pointers ➔ No Ownership unique_ptr shared_ptr weak_ptr Smart pointers are responsible for the memory management of the object to which they point! After C++11, there are Smart Pointers! ➔ Automatic Memory Management ➔ Developer is free from memory management ● Less bugs from object leaks ● Objects existence is self managed ● Increased Code robustness
  • 46. Smart Pointers Unique Pointers→ 46 60/ More information at: http://en.cppreference.com/w/cpp/memory/unique_ptr Unique pointers cannot be copied! 1 to 1 relationship with object Result Pointer is created with object constructor arguments Context is closed, pointer and object are destroyed Pointer is created, with object. Pointer is transferred to Method Method execution ends, pointer and object are destroyed. Unique pointers cost ZERO in performance!
  • 47. Smart Pointers Shared Pointers→ 47 60/ More information at: http://en.cppreference.com/w/cpp/memory/shared_ptr Result Pointer 1 is created without object Pointer 2 is created with object Pointer 2 is copied to pointer 1, reference counter is increased in 1. Context is closed, pointer 2 is destroyed Context is closed, pointer 1 and object are destroyed. Shared pointers can be copied! Many to 1 relationship with object ➔ Shared pointers track object ownership, using a per-object, shared, internal reference counter. ➔ When the counter reaches zero, the object is destroyed. Beware! Shared pointers are vulnerable to circular reference issues
  • 48. Smart Pointers Weak Pointers→ 48 60/ More information at: http://en.cppreference.com/w/cpp/memory/weak_ptr Weak pointer is created Shared pointer 1 is created with object Shared pointer 1 info related to object is copied into weak pointer. Verification if object still exists (true) Shared pointer 2 is created from Weak pointer. Context is closed, pointer 2 is destroyed Context is closed, pointer 1 and object are destroyed Verification if object no longer exists (true) Weak pointers have no object ownership! Used to avoid circular reference issues. ➔ To access an object pointed by weak pointers, it is required to create a Shared Pointer. ➔ Shared pointer creation may fail, if object no longer exists! Result
  • 49. C++ Generic Containers→ 49 60/ The power of the Standard Template Library, is easily seen in its Generic Data containers. Generic Containers (some of them) ➔ Arrays <array> ➔ Vectors <vector> ➔ Lists <list> ➔ Maps <map> ➔ Sets <set> ➔ Stacks <stack> ➔ Queues <queue> More information at: http://en.cppreference.com/w/cpp/container
  • 50. C++ Generic Algorithms→ 50 60/ Generic Algorithms for Generic Structures. ➔ Searching ● Binary Search ➔ Sorting ➔ Swapping ➔ Copying ➔ Partitioning ➔ Set Operations ➔ Minimum/Maximum Operations ➔ Numeric Operations More information at: http://en.cppreference.com/w/cpp/algorithm Result Available at <algorithm>
  • 51. C++ Threads and Locks→ 51 60/ More information at: http://en.cppreference.com/w/cpp/thread/thread http://en.cppreference.com/w/cpp/thread/mutex ➔ Type declaration for the thread “main” ➔ Number of available hardware threads ➔ Shared counter ➔ List of Threads ➔ Threads will increase the counter, until it reaches 1000000 ➔ Thread object creation ➔ Moving thread to the list, NOT COPY! ➔ Master thread will wait for working threads to end ➔ Final counter value is printed Available at <thread>
  • 52. C++ Threads and Locks→ 52 60/ Result Result More information at: http://en.cppreference.com/w/cpp/thread/thread http://en.cppreference.com/w/cpp/thread/mutex But… there is a synchronization problem! For 90% of the trials, the result is correct! But the problem is the remaining 10%...
  • 53. C++ Threads and Locks→ 53 60/ We solve the problem with a mutex! Before accessing the shared resource, the thread locks the access When it no longer needs the resource, it releases the lock! Result Available at <mutex>
  • 54. 4th Part 54 60/ C++14 Extreme Properties It ain’t what you don’t know that gets you into trouble. It’s what you know for sure that just ain’t so. – Mark Twain WARNING If you don’t understand at first, don’t worry… neither did I This is mostly to show C++14 capabilities
  • 55. C++ Templates & SFINAE→ 55 60/ C++ provides a Meta-programming language ➔ It is very helpful for automatic code generation! This language is implemented using templates ➔ The base of STL ➔ Allow the creation of Generic Code ➔ Developers focus on algorithms and establish boundaries for type deduction Substitution Failure Is Not An Error (SFINAE) ➔ This rule applies during overloading resolution of function templates. ➔ Specializations are discarded, when the compiler fails to substitute the types in the template parameters. More information at: http://en.cppreference.com/w/cpp/language/templates http://en.cppreference.com/w/cpp/language/partial_specialization http://en.cppreference.com/w/cpp/language/sfinae Template Processing 1st ➔ Recursive template code evaluation ➔ Template Parameter Substitution ● SFINAE validation 2nd ➔ Code Inlining and Compilation
  • 56. C++ Automatic Type Deduction→ 56 60/ Result ➔ Just a “magic method” that outputs the name of the object type Template with automatic type deduction, with type identification from operation. SFINAE rule discards incorrect template Automatic type deduction from provided value Automatic type deduction from make_shared operation More information at: http://en.cppreference.com/w/cpp/language/auto
  • 57. C++ Templates with Type Traits→ 57 60/ Result More information at: http://en.cppreference.com/w/cpp/header/type_traits Templates with Type Traits Recursive Templates Available at <type_traits>
  • 58. C++14 Efficient Modern Development→ 58 60/ Summarizing important C++ modern features ➔ Cleaner and Sane Syntax ➔ Lambda Functions ● Powerful way to organize code and reduce namespace pollution. ➔ Move Constructor and Move Semantics ● Allows zero-copy transfer of attribute information ➔ Smart Pointers ● Automatic Memory Management with Ownership Management ➔ Improved Generic Containers ● Updated with Move semantics ➔ Improved Generic Algorithms ● Lots of generic algorithms ● C++17 will bring Parallel Algorithms ➔ Automatic Type Deduction ➔ Templates Type Traits ● Type boundary capabilities
  • 59. C++14 Resources→ 59 60/ Websites ➔ http://www.cppreference.com ➔ http://www.cplusplus.com/ Recommended Books ➔ The C++ Programming Language 4th Edition (Addison.Wesley Jun 2013) ➔ Programming Principles and Practice Using C++, 2nd Edition (Addison Wesley, 2014) ➔ Professional C++ 3rd Edition (2014) ➔ Effective Modern C++ (OReilly2014) ➔ C++ For Dummies, 7th Edition (2014) ➔ A Tour of C++ (2013 Addison Wesley) Libraries and Frameworks worth of checking out ➔ Boost ➔ POCO ➔ QT5
  • 60. C++14 We are done!→ 60 60/ Thank you for your patience!