c++14 - modern programming for demanding times

60
NAP Talks C++14: Modern Programming for Demanding Times Speaker: Carlos Miguel Ferreira Position: PhD Student and IT Researcher Contact: [email protected]

Upload: carlos-miguel-ferreira

Post on 16-Jan-2017

280 views

Category:

Software


0 download

TRANSCRIPT

Page 1: C++14 - Modern Programming for Demanding Times

NAP TalksC++14: Modern Programming for Demanding Times

Speaker: Carlos Miguel FerreiraPosition: PhD Student and IT ResearcherContact: [email protected]

Page 2: C++14 - Modern Programming for Demanding Times

Layout

1st Part – Some History➔ Some background about C++ ➔ Philosophy➔ The International Standard➔ Boost➔ Standard Template Library

BreakTime

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

Page 3: C++14 - Modern Programming for Demanding Times

1st Part 3 60/

C++14

History, Philosophy and Standards

Why waste time learningwhen ignorance is instantaneous?

– Hobbes

Page 4: C++14 - Modern Programming for Demanding Times

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...

Page 5: C++14 - Modern Programming for Demanding Times

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

Page 6: C++14 - Modern Programming for Demanding Times

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.

Page 7: C++14 - Modern Programming for Demanding Times

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...

Page 8: C++14 - Modern Programming for Demanding Times

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)

Page 9: C++14 - Modern Programming for Demanding Times

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

Page 10: C++14 - Modern Programming for Demanding Times

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

Page 11: C++14 - Modern Programming for Demanding Times

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.

Page 12: C++14 - Modern Programming for Demanding Times

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

Page 13: C++14 - Modern Programming for Demanding Times

2nd Part 13 60/

C++14

Lets start with the basics!A programmer is a machine

for turning caffeine into code.– A programmer

Page 14: C++14 - Modern Programming for Demanding Times

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

Page 15: C++14 - Modern Programming for Demanding Times

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 ExceptionI will talk about them later...

std::exception is throwed.

Page 16: C++14 - Modern Programming for Demanding Times

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.

Page 17: C++14 - Modern Programming for Demanding Times

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

Page 18: C++14 - Modern Programming for Demanding Times

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

Page 19: C++14 - Modern Programming for Demanding Times

Standard Types Fixed Width Integers→ 19 60/

Fixed Width Integer types(all within std::)

int8_tint16_tint32_tint64_t

int_fast8_tint_fast16_tint_fast32_tint_fast64_t

int_least8_tint_least16_tint_least32_tint_least64_t

intmax_t

intptr_t

More information at: http://en.cppreference.com/w/cpp/types/integer

uint8_tuint16_tuint32_tuint64_t

uint_fast8_tuint_fast16_tuint_fast32_tuint_fast64_t

uint_least8_tuint_least16_tuint_least32_tuint_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

Page 20: C++14 - Modern Programming for Demanding Times

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

Page 21: C++14 - Modern Programming for Demanding Times

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

Page 22: C++14 - Modern Programming for Demanding Times

Methods 22 60/

Result

Method Overloading

The names are equal➔ Different signatures for equivalent behaviours➔ Keep code clean, elegant!➔ No method naming Hell!

Page 23: C++14 - Modern Programming for Demanding Times

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...

Page 24: C++14 - Modern Programming for Demanding Times

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

Page 25: C++14 - Modern Programming for Demanding Times

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.

Page 26: C++14 - Modern Programming for Demanding Times

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.

Page 27: C++14 - Modern Programming for Demanding Times

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

MemoryAllocation Object

Object Instantiation

Object Blueprints

Page 28: C++14 - Modern Programming for Demanding Times

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!

Page 29: C++14 - Modern Programming for Demanding Times

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.

Page 30: C++14 - Modern Programming for Demanding Times

Classes Constructors and Destructor→ 30 60/

Result

Private unique pointer to string withpointer default initialization

Copy Constructor

Move Constructor

Destructor

Default Constructor

Explicit String Copy Constructor

Acessing unique pointer after moveUndefined Behaviour!

More information at: http://en.cppreference.com/w/cpp/language/classes

Page 31: C++14 - Modern Programming for Demanding Times

Classes Implicit Copy Constructor→ 31 60/

Implicit constructionImplicit constructors can be a source of confusion.

B as a copy constructor for AC 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

Page 32: C++14 - Modern Programming for Demanding Times

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.

Page 33: C++14 - Modern Programming for Demanding Times

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

Page 34: C++14 - Modern Programming for Demanding Times

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

Page 35: C++14 - Modern Programming for Demanding Times

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

DisclaimerI will not talk about Multiple-Inheritance

It is a complex world...

Page 36: C++14 - Modern Programming for Demanding Times

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

Page 37: C++14 - Modern Programming for Demanding Times

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).

Page 38: C++14 - Modern Programming for Demanding Times

Classes Non-Polymorphic Inheritance→ 38 60/

Person_Name and Dog_Name inherit from Name

There are no Virtual members/constructs

Page 39: C++14 - Modern Programming for Demanding Times

Classes Non-Polymorphic Inheritance→ 39 60/

Result

No Polymorphism➔ Methods are not

overridden➔ There is no V-Table

Page 40: C++14 - Modern Programming for Demanding Times

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.

Page 41: C++14 - Modern Programming for Demanding Times

Casting in C++ 41 60/

C++ provides 4 types of CastingStatic 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

Page 42: C++14 - Modern Programming for Demanding Times

42 60/

Lets take a break!

Questions?

Page 43: C++14 - Modern Programming for Demanding Times

3rd Part 43 60/

C++14

Increasing the complexity...For every complex problem,

there is an answer that isclear, simple, and wrong.

– H. L. Mencken

Page 44: C++14 - Modern Programming for Demanding Times

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.

Page 45: C++14 - Modern Programming for Demanding Times

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_ptrSmart 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

Page 46: C++14 - Modern Programming for Demanding Times

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!

Page 47: C++14 - Modern Programming for Demanding Times

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

Page 48: C++14 - Modern Programming for Demanding Times

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 destroyedContext 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

Page 49: C++14 - Modern Programming for Demanding Times

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

Page 50: C++14 - Modern Programming for Demanding Times

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>

Page 51: C++14 - Modern Programming for Demanding Times

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>

Page 52: C++14 - Modern Programming for Demanding Times

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%...

Page 53: C++14 - Modern Programming for Demanding Times

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>

Page 54: C++14 - Modern Programming for Demanding Times

4th Part 54 60/

C++14

Extreme PropertiesIt 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

WARNINGIf you don’t understand at first, don’t worry… neither did I

This is mostly to show C++14 capabilities

Page 55: C++14 - Modern Programming for Demanding Times

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

Page 56: C++14 - Modern Programming for Demanding Times

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

Page 57: C++14 - Modern Programming for Demanding Times

C++ Templates with Type Traits→ 57 60/

Result

More information at: http://en.cppreference.com/w/cpp/header/type_traits

Templates with Type Traits

RecursiveTemplates

Available at <type_traits>

Page 58: C++14 - Modern Programming for Demanding Times

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

Page 59: C++14 - Modern Programming for Demanding Times

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

Page 60: C++14 - Modern Programming for Demanding Times

C++14 We are done!→ 60 60/

Thank you for your patience!