SlideShare a Scribd company logo
1 of 107
Download to read offline
C++: A FAST TOUR
OF A FAST LANGUAGE
ADRIAN OSTROWSKI
4DEVELOPERS, SEPTEMBER 25 , 2018TH
• spent childhood in crop fields
• 8 years in the software field, 6 years in C++
• west const propagator
• interested in Agile, quality and performance
• lifelong learner
• music lover
• gamer
whoami
2
What we will talk about today?
• the fat and the gaunt years of C++
• why the language currently experiences its renaissance
• what is Modern C++ and why you should care
• how the language evolved and where will it go from here
• how the ecosystem evolved along with the language
What we won't talk about?
• (too much) hard stuff
• why C++ is "better" or "worse" than ${OTHER_LANG}
AGENDA
3
A PINCH OF HISTORY
HOW C++ STARTED
5
1979
6
THE SAME NOW AS WHEN THE LANGUAGE WAS CREATED
1 There should be no language beneath C++ (except assembly)
2 You only pay for what you use
3 Offer high-level abstractions at low cost (strong aim for zero-cost)
PHILOSOPHY OF C++
7
1985
8
THE '90S - STL
9
THE '90S - RISE OF OOP
10
THE 2000S - COFFEE-BASED LANGUAGES
11
SHIFT OF PRIORITIES
• Battery life
• Performance per watt
• Low memory consumption
• Retaining responsiveness
MOBILE PLATFORMS
12
SCALE CHANGES EVERYTHING
• Low costs of software compared to total costs
• Performance per watt
• Optimizations scale through servers
CLOUD PLATFORMS
13
EMBEDDED PLATFORMS
14
• performance (game development, high-frequency trading)
• mission-critical systems, e.g. aeroplanes
• OS development
• automotive industry
• blockchain
• building blocks, e.g. for AI and ML
WHERE ELSE IS C++ USED?
15
HOW MUCH DOES C++ MATTER NOWADAYS?
16
MODERN C++
• C++11?
WHAT IS MODERN C++?
18
• C++11?
• C++14?
WHAT IS MODERN C++?
18
• C++11?
• C++14?
• C++17?
WHAT IS MODERN C++?
18
• C++11?
• C++14?
• C++17?
• Whatever the newest standard is?
WHAT IS MODERN C++?
18
• C++11?
• C++14?
• C++17?
• Whatever the newest standard is?
NOPE
WHAT IS MODERN C++?
18
• C++11?
• C++14?
• C++17?
• Whatever the newest standard is?
NOPE
Modern C++ is not about the standard
WHAT IS MODERN C++?
18
• C++11?
• C++14?
• C++17?
• Whatever the newest standard is?
NOPE
Modern C++ is not about the standard
It's a philosophy of code design
WHAT IS MODERN C++?
18
• C++11?
• C++14?
• C++17?
• Whatever the newest standard is?
NOPE
Modern C++ is not about the standard
It's a philosophy of code design
C++11 was heavily influenced by industry practices and popular libraries
WHAT IS MODERN C++?
18
Q: WHAT YEAR IS THIS BOOK FROM?
19
Modern C++ isn't afraid of:
• RAII
SO HOW IT'S DIFFERENT THAN "OLD-STYLE" C++?
20
Modern C++ isn't afraid of:
• RAII
• reuse of (standard) library components
SO HOW IT'S DIFFERENT THAN "OLD-STYLE" C++?
20
Modern C++ isn't afraid of:
• RAII
• reuse of (standard) library components
• templates and metaprogramming
SO HOW IT'S DIFFERENT THAN "OLD-STYLE" C++?
20
Modern C++ isn't afraid of:
• RAII
• reuse of (standard) library components
• templates and metaprogramming
• mixing programming paradigms
SO HOW IT'S DIFFERENT THAN "OLD-STYLE" C++?
20
Have you ever leaked a resource?
RESOURCE ACQUISITION IS INITIALIZATION
21
Have you ever leaked a resource?
Have you ever double-freed a resource?
RESOURCE ACQUISITION IS INITIALIZATION
21
Have you ever leaked a resource?
Have you ever double-freed a resource?
Had a hard time releasing them if an exception occurs?
RESOURCE ACQUISITION IS INITIALIZATION
21
Have you ever leaked a resource?
Have you ever double-freed a resource?
Had a hard time releasing them if an exception occurs?
RAII takes the burden of resource handling from the programmer.
RESOURCE ACQUISITION IS INITIALIZATION
21
template<typename T>
class SmartPtr : NonCopyable {
public:
explicit SmartPtr(T* ptr = nullptr) : ptr_{ptr} {}
SmartPtr(const SmartPtr& other) = delete;
SmartPtr& operator=(const SmartPtr& other) = delete;
~SmartPtr() { delete ptr_; }
T& operator*() { return *ptr_; }
const T& operator*() const { return *ptr_; }
T* operator->() { return ptr_; }
const T* operator->() const { return ptr_; }
private:
T* ptr_;
};
RAII EXAMPLE: A SIMPLE SMART POINTER
22
Who works in a company that has/had it's own string implementation?
QUICK Q
23
• generic programming
• policy-based design
• library reuse
REUSE OF (STANDARD) LIBRARY COMPONENTS
24
template<typename T, typename OverflowPolicy>
class Treasury {
public:
void add(T amount) {
if (OverflowPolicy::Check(treasure_, amount)) {
treasure_ += amount;
}
}
bool has_enough_value() {
// TODO: become less greedy
return false;
}
// ...
private:
T treasure_{};
};
POLICY-BASED DESIGN
25
template<typename T>
struct RobinHoodPolicy {
bool Check(T& treasure, T amount) {
auto space = std::numeric_limits<T>::max() - treasure_;
if (space < amount) {
Steal(amount - space);
}
return true;
}
};
using NottinghamTreasury = Treasury<int, RobinHoodPolicy<int>>;
POLICY-BASED DESIGN, CONT'D
26
Some great and free for commercial use libraries:
• Boost
• Abseil
• EASTL
• BDE/BSL
• Folly
REUSE EXISTING LIBRARIES
27
Some great and free for commercial use libraries:
• Boost
• Abseil
• EASTL
• BDE/BSL
• Folly
Other libraries can be pulled by package managers like Conan.
REUSE EXISTING LIBRARIES
27
CONANFILE.TXT
[requires]
range-v3/0.3.6@ericniebler/stable
[generators]
cmake
CONAN
28
CMAKELISTS.TXT
cmake_minimum_required(VERSION 3.12)
project(my_precious)
include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)
conan_basic_setup(TARGETS)
add_executable(my_precious src/main.cpp)
target_compile_features(my_precious PUBLIC cxx_std_14)
target_link_libraries(my_precious CONAN_PKG::range-v3) # also handles includes
CONSOLE
$ mkdir build && cd build
$ conan install ..
$ cmake .. -G "Visual Studio 15 Win64"
CONAN, CONT'D
29
template<int N>
struct Factorial {
static const int value = N * Factorial<N-1>::value;
};
template<>
struct Factorial<0> {
static const int value = 1;
};
int main() {
std::cout << Factorial<12>::value << 'n';
}
MODERN C++: TEMPLATES AND METAPROGRAMMING
30
template<int N>
struct Factorial {
static const int value = N * Factorial<N-1>::value;
};
template<>
struct Factorial<0> {
static const int value = 1;
};
int main() {
std::cout << Factorial<12>::value << 'n';
}
C++ shifts more and more to compile-time computations
MODERN C++: TEMPLATES AND METAPROGRAMMING
30
constexpr int factorial(int n) {
int result = n;
while (n > 1)
result *= --n;
return result;
}
static_assert(factorial(4) == 24);
int main() {
std::cout << factorial(12) << 'n';
}
CONSTEXPR FUNCTIONS
31
constexpr int factorial(int n) {
int result = n;
while (n > 1)
result *= --n;
return result;
}
static_assert(factorial(4) == 24);
int main() {
std::cout << factorial(12) << 'n';
}
Compile-time gets easier with newer standards
CONSTEXPR FUNCTIONS
31
Most use C++ as procedural/object-oriented, imperative language
MODERN C++: MIXING PROGRAMMING PARADIGMS
32
Most use C++ as procedural/object-oriented, imperative language
It allows more than that.
MODERN C++: MIXING PROGRAMMING PARADIGMS
32
• templates
• most of the standard library
• auto keyword
• template metaprogramming
• constexpr functions
GENERIC PROGRAMMING
33
DECLARATIVE C++: RANGES V3
34
int main() {
using namespace std::literals;
using namespace ranges;
auto is_even = [](int x) { return x % 2 != 0; };
auto to_string = [](int x) { return std::to_string(x); };
auto my_range = view::ints
| view::filter(is_even)
| view::drop(1)
| view::take(3)
| view::reverse
| view::transform(to_string);
std::cout << ranges::accumulate(my_range, ""s) << 'n';
}
DECLARATIVE C++: RANGES V3
34
// functions as 1st class citizens
auto pow2 = [] (auto x) { return x*x; };
// higher order functions
auto compose = [](auto f1, auto f2) {
return [&] (auto ...params) {
return f2(f1(std::forward<decltype(params)>(params)...));
};
};
std::cout << compose(std::plus<>{}, pow2)(2, 3); // prints 25
FUNCTIONAL C++
35
TO SUM UP, MODERN C++ RESULTS IN
36
• safer and cleaner code
TO SUM UP, MODERN C++ RESULTS IN
36
• safer and cleaner code
• which is faster to develop
TO SUM UP, MODERN C++ RESULTS IN
36
• safer and cleaner code
• which is faster to develop
• and faster at runtime!
TO SUM UP, MODERN C++ RESULTS IN
36
• safer and cleaner code
• which is faster to develop
• and faster at runtime!
And it plays great with recent C++ standards
TO SUM UP, MODERN C++ RESULTS IN
36
LANGUAGE EVOLUTION
THE PAST
LANGUAGE EVOLUTION
THE GAME CHANGER - C++11
• Passing ownership between objects using std::move
std::unique_ptr<T> up(new T{});
std::unique_ptr<T> up2 = std::move(up);
foo(std::move(up2));
MOVE SEMANTICS
39
• Passing ownership between objects using std::move
std::unique_ptr<T> up(new T{});
std::unique_ptr<T> up2 = std::move(up);
foo(std::move(up2));
• Better performance by avoiding copies
MOVE SEMANTICS
39
• Passing ownership between objects using std::move
std::unique_ptr<T> up(new T{});
std::unique_ptr<T> up2 = std::move(up);
foo(std::move(up2));
• Better performance by avoiding copies
• Moving creates an r-value reference, similarly to creating a new object
MOVE SEMANTICS
39
• Templates accepting arbitrary number of arguments, e.g. for creating tuples
• Example: make_unique in C++11
template<class T, class... Args>
inline std::unique_ptr<T> make_unique(Args&&... args) {
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
VARIADIC TEMPLATES
40
• Lightweight list of values
• Can be used to construct containers in one go
void foo(const std::vector<int> &v);
auto numbers = { 1, 2, 3 }; // std::initializer_list<int>
foo({numbers});
foo({3, 4, 5});
foo({});
std::map<int, std::string> my_map{
{ 1, "one" },
{ 2, "two" }
};
INITIALIZER LISTS
41
• Compile-time checks with simple error messages
static_assert(sizeof(void *) * CHAR_BIT == 8, "64-bit platform required");
template <class T>
T calculate(T x, T y) {
static_assert(std::is_arithmetic<T>::value,
"Can't calculate using non-numerical types");
// ...
}
STATIC ASSERTIONS
42
• automatic type deduction for variables, return types, etc.
• use it for correctness – avoid accidental type conversions
• use if for generic programming – easier maintenance in case the used type changes
• use it for readability - less is more
• use it for safety – you can’t forget to initialize it
// no changes when get_widget() returns unique_ptr instead of shared_ptr
auto widget = get_widget();
auto it = map.find(42); // auto vs std::map<int, std::string>::iterator;
auto func = [](int x) { return x * 2; };
auto KEYWORD
43
• functions are now first class citizens
• excellent for use with standard functions
[](){ std::cout << "Hello Lambda World!n"; };
int x = 1;
auto f1 = [&x] { return x *= 2; }; // modify original x
auto f2 = [x] () mutable { return x *= 2; }; // modify copy
std::vector<int> v{1, -2, 3};
std::sort(begin(v), end(v), [](int a, int b) { return b*b > a*a });
LAMBDA EXPRESSIONS
44
std::vector<int> v{1, 2, 3, 4, 5};
for (int i: v) {
std::cout << i << ' ';
}
for (int& i: v) {
i *= 2;
}
RANGE-BASED FOR LOOPS
45
• std::thread
• std::atomic<T>
• std::mutex and guards
CONCURRENCY FACILITIES
46
using namespace std::chrono;
auto start = steady_clock::now(); // time_point<steady_clock>
// insert measured work here
auto end = steady_clock::now();
auto micros = duration_cast<microseconds>(end-start); // duration<long, std::micro>
std::cout << micros.count() << 'n';
auto blink_of_an_eye = std::chrono::milliseconds(300);
// more convenient since C++14
using namespace std::chrono::literals;
auto day = 24h;
std::chrono
47
• std::array
• std::unordered_map
• std::unordered_set
• std::tuple
NEW CONTAINERS
48
LANGUAGE EVOLUTION
THE NEAR PAST - C++14
GENERIC LAMBDAS
auto comparator = [](auto i, auto j) { return (i > j); };
auto ints = std::vector<int>{ 1, 12, 9, 10 };
std::sort(begin(ints), end(ints), comparator);
auto strings = std::vector<std::string>{"cat", "dog", "ox", "aardvark"};
std::sort(begin(strings), end(strings), comparator);
LAMBDA IMPROVEMENTS
50
LANGUAGE EVOLUTION
THE PRESENT - C++17
template<typename... Args>
auto multiply(Args... args) {
return (... * args);
}
void foo() {
return multiply(1.f, 2.5, 4);
}
FOLD EXPRESSIONS
52
// before
template<int N>
constexpr int fibonacci() {return fibonacci<N-1>() + fibonacci<N-2>(); }
template<>
constexpr int fibonacci<1>() { return 1; }
template<>
constexpr int fibonacci<0>() { return 0; }
CONSTEXPR IF
53
// before
template<int N>
constexpr int fibonacci() {return fibonacci<N-1>() + fibonacci<N-2>(); }
template<>
constexpr int fibonacci<1>() { return 1; }
template<>
constexpr int fibonacci<0>() { return 0; }
// after
template<int N>
constexpr int fibonacci() {
if constexpr (N>=2)
return fibonacci<N-1>() + fibonacci<N-2>();
else
return N;
}
CONSTEXPR IF
53
// in some class
std::vector v{1, 2, 3};
std::mutex mut;
// in some function
if (auto lock = std::scoped_lock{mut}; !v.empty()) {
v.pop_back();
}
IFS AND SWITCHES WITH INITIALIZERS
54
// in some class
std::vector v{1, 2, 3};
std::mutex mut;
// in some function
if (auto lock = std::scoped_lock{mut}; !v.empty()) {
v.pop_back();
}
switch (Command cmd = read_command(); cmd.type) { /* ... */}
IFS AND SWITCHES WITH INITIALIZERS
54
// in some class
std::vector v{1, 2, 3};
std::mutex mut;
// in some function
if (auto lock = std::scoped_lock{mut}; !v.empty()) {
v.pop_back();
}
switch (Command cmd = read_command(); cmd.type) { /* ... */}
if (auto [iter, success] = myset.insert("X"); success) {/* ... */}
IFS AND SWITCHES WITH INITIALIZERS
54
auto v = std::variant<int, string>{42};
std::get<int>(v); // returns 42
std::get<0>(v); // returns 42
std::get<double>(v); // compile-time error
v = "not an int";
std::get<int>(v); // throws std::bad_variant_access
STD::VARIANT - A TYPE-SAFE UNION
55
using my_types = std::variant<int, std::string, double>;
std::vector<my_types> vec{"XYZ", 1337, 21.37};
for(auto& v: vec) {
v = std::visit([](auto&& arg) -> my_types { return arg + arg; }, v);
}
struct TypeNamingVisitor {
void operator()(int&) { std::cout << "int"; }
void operator()(std::string&) { std::cout << "string"; }
void operator()(double&) { std::cout << "double"; }
};
std::visit(TypeNamingVisitor{}, vec.front());
STD::VARIANT - VISITATION
56
What can you tell about the following function?
int* parse_number(const std::string& input);
STD::OPTIONAL FOR CLEAN INTERFACES
57
What can you tell about the following function?
int* parse_number(const std::string& input);
How about this one?
int parse_number(const std::string& input);
STD::OPTIONAL FOR CLEAN INTERFACES
57
What can you tell about the following function?
int* parse_number(const std::string& input);
How about this one?
int parse_number(const std::string& input);
What about this one?
std::optional<int> parse_number(const std::string& input);
STD::OPTIONAL FOR CLEAN INTERFACES
57
struct User {
std::string name;
std::string surname;
std::optional<std::string> nickname;
};
User{"Eldrick", "Woods", "Tiger"};
User{"John", "Smith", std::nullopt};
STD::OPTIONAL FOR CLEAN INTERFACES
58
struct User {
std::string name;
std::string surname;
std::optional<std::string> nickname;
};
User{"Eldrick", "Woods", "Tiger"};
User{"John", "Smith", std::nullopt};
void login(const User& user, std::optional<year_month_day> passwordExpiration);
STD::OPTIONAL FOR CLEAN INTERFACES
58
// before
void foo(const char *ptr);
void foo(const char *ptr, size_t length);
void foo(const std::string&);
// after
void foo(std::string_view);
STD::STRING_VIEW
59
Which is faster? Why?
void foo(const std::string& str);
foo("A quick brown fox jumps over the lazy dog");
// vs
void bar(std::string_view);
bar("A quick brown fox jumps over the lazy dog");
STD::STRING_VIEW
60
Execution policies:
• sequential (std::seq),
• parallel (std::par),
• parallel with vectorization (std::par_unseq).
PARALLEL ALGORITHMS
61
Execution policies:
• sequential (std::seq),
• parallel (std::par),
• parallel with vectorization (std::par_unseq).
USAGE
std::algorithm_name(policy, usual_arguments...);
PARALLEL ALGORITHMS
61
• adjacent_{difference, find}
• {all, any, none}_of
• copy{, _if, _n}
• count{, _if}
• equal
• fill{, _n}
• find{, _end, _first_of, _if,
_if_not}
• generate{, _n}
• includes
• inner_product
• inplace_merge
PARALLEL ALGORITHMS - SUPPORTED EXISTING ALGOS
• is_{heap, heap_until, partitioned,
sorted, sorted_until}
• lexicographical_compare
• {max, min, minmax}_element
• merge
• mismatch
• move
• nth_element
• partial_sort{, _copy}
• partition{, _copy}
• remove{, _copy, _if, _copy_if}
• replace{, _copy, _if, _copy_if}
• reverse{, _copy}
• rotate{, _copy}
• search{, _n}
• set_{difference, intersection,
symmetric_difference, union}
• sort
• stable_{partition, sort}
• swap_ranges
• transform
• uninitialized_{copy, copy_n, fill,
fill_n}
• unique{, _copy}
62
LANGUAGE EVOLUTION
THE FUTURE
• type-checking in templates
• simpler template error messages
• easier selection of overloads and specializations
• constraining automatic type deduction
template<typename T>
concept Hashable = requires(T a) {
{ std::hash<T>{}(a) } -> std::size_t;
};
template<Hashable Key>
auto get_bucket(Key key, std::size_t max_buckets) -> std::size_t;
CONCEPTS - C++20
64
std::list<int> l = {2, 1, 3};
std::sort(l.begin(), l.end());
In instantiation of 'void std::__sort(_RandomAccessIterator, _RandomAccessIterator,
_Compare) [with _RandomAccessIterator = std::_List_iterator<int>; _Compare =
__gnu_cxx::__ops::_Iter_less_iter]':
error: no match for 'operator-' (operand types are 'std::_List_iterator<int>'
and 'std::_List_iterator<int>')
std::__lg(__last - __first) * 2,
// few dozens more lines of error messages
error: cannot call function 'void std::sort(_RAIter, _RAIter)
[with _RAIter = std::_List_iterator<int>]'
note: concept 'RandomAccessIterator()' was not satisfied
CONCEPTS - ERROR MESSAGES
65
void foo(const std::vector<int>& v)
[[expects: !v.empty()]]
[[ensures audit v2: is_sorted(v2)]] {
int x = g();
[[assert: x > 0]]
auto v2 = bar(v, x);
return v2;
}
• Possible enforcing levels are: default, audit, and axiom
CONTRACTS - C++20
66
generator<int> even_numbers() {
auto current = 0;
while (true) {
co_yield current;
current += 2;
}
}
COROUTINES - C++20/23
67
generator<int> even_numbers() {
auto current = 0;
while (true) {
co_yield current;
current += 2;
}
}
auto find_line(std::string resource, std::string key)
-> std::future<std::expected<std::string>> {
while (auto line = co_await fetch_line(co_await load(resource))) {
if (contains(line, key))
co_return line;
}
co_return std::unexpected(not_found(resource));
}
COROUTINES - C++20/23
67
• Import a module instead of #including <files>
• Much, much faster compile times
• No more splitting code between header and cpp files
• Easier package management
MODULES - C++20/23
68
• Generate classes of classes
• Examples: interface, value, flag_enum, property, qt::signal & qt::slot
constexpr void interface(meta::type target, const meta::type source) {
compiler.require(source.variables().empty(), "interfaces can't contain data");
for (auto f : source.functions()) {
if (!f.has_access()) f.make_public();
f.make_pure_virtual();
->(target) f;
}
->(target) { virtual ~(source.name()$)() noexcept {} }
}
interface Shape {
string name() const;
/*...*/
};
METACLASSES
69
What problems did we have?
• compiles were slow
• compile errors were complicated
• templates were hard to debug
• memory leaks
• no central place to go for news, papers etc.
ECOSYSTEM EVOLUTION - CAUSES
70
• Boost
• CMake
• Conan
• Clang - for better developer productivity (faster compile times, better error messages, side effects:
REPL, better GCC perf)
• Sanitizers & Valgrind
• Metashell
• A plethora of blogs, books, conferences, online videos.
ECOSYSTEM EVOLUTION - EFFECTS
71
• Awesome C++
• isocpp.org
• cppreference.com
• Clang
RESOURCES
72
QUESTIONS
AND (HOPEFULLY) ANSWERS
TANKS FOR COMING
74
• Bjarne Stroustrup's photo by Julia Kryuchkova (edited), CC-BY-SA 2.5, Wikipedia
• Bell Labs Holmdel Complex by Lee Beaumont, retouched by MBisanz & Kylu, CC-BY-SA 2.0,
Wikipedia
• Livraria do Senado by Senado Federal, CC-BY 2.0, Wikipedia
• Microsoft Windows 95 screenshot, used with permission from Microsoft
• Working lat(t)e by Kuba Bożanowski, CC-BY 2.0, Flickr
• Alexander Stepanov's photo by Paul R. McJones, CC-BY-SA 3.0, Wikipedia
• IEEE Spectrum Ranking
• Tanks by Roger May, CC-BY-SA 2.0, Geograph.co.uk
ATTRIBUTIONS
75

More Related Content

What's hot

Comparing On-The-Fly Accelerating Packages: Numba, TensorFlow, Dask, etc
Comparing On-The-Fly Accelerating Packages: Numba, TensorFlow, Dask, etcComparing On-The-Fly Accelerating Packages: Numba, TensorFlow, Dask, etc
Comparing On-The-Fly Accelerating Packages: Numba, TensorFlow, Dask, etcYukio Okuda
 
How to easily find the optimal solution without exhaustive search using Genet...
How to easily find the optimal solution without exhaustive search using Genet...How to easily find the optimal solution without exhaustive search using Genet...
How to easily find the optimal solution without exhaustive search using Genet...Viach Kakovskyi
 
Introduction to Polyhedral Compilation
Introduction to Polyhedral CompilationIntroduction to Polyhedral Compilation
Introduction to Polyhedral CompilationAkihiro Hayashi
 
PyCon Ukraine 2016: Maintaining a high load Python project for newcomers
PyCon Ukraine 2016: Maintaining a high load Python project for newcomersPyCon Ukraine 2016: Maintaining a high load Python project for newcomers
PyCon Ukraine 2016: Maintaining a high load Python project for newcomersViach Kakovskyi
 
CLaSH HIW 2014
CLaSH HIW 2014CLaSH HIW 2014
CLaSH HIW 2014baaijcpr
 

What's hot (8)

Make2win 線上課程分析
Make2win 線上課程分析Make2win 線上課程分析
Make2win 線上課程分析
 
C++ Coroutines
C++ CoroutinesC++ Coroutines
C++ Coroutines
 
Comparing On-The-Fly Accelerating Packages: Numba, TensorFlow, Dask, etc
Comparing On-The-Fly Accelerating Packages: Numba, TensorFlow, Dask, etcComparing On-The-Fly Accelerating Packages: Numba, TensorFlow, Dask, etc
Comparing On-The-Fly Accelerating Packages: Numba, TensorFlow, Dask, etc
 
How to easily find the optimal solution without exhaustive search using Genet...
How to easily find the optimal solution without exhaustive search using Genet...How to easily find the optimal solution without exhaustive search using Genet...
How to easily find the optimal solution without exhaustive search using Genet...
 
Yacf
YacfYacf
Yacf
 
Introduction to Polyhedral Compilation
Introduction to Polyhedral CompilationIntroduction to Polyhedral Compilation
Introduction to Polyhedral Compilation
 
PyCon Ukraine 2016: Maintaining a high load Python project for newcomers
PyCon Ukraine 2016: Maintaining a high load Python project for newcomersPyCon Ukraine 2016: Maintaining a high load Python project for newcomers
PyCon Ukraine 2016: Maintaining a high load Python project for newcomers
 
CLaSH HIW 2014
CLaSH HIW 2014CLaSH HIW 2014
CLaSH HIW 2014
 

Similar to C++: a fast tour of a fast language

C++11 Was Only the Beginning
C++11 Was Only the BeginningC++11 Was Only the Beginning
C++11 Was Only the BeginningMateusz Pusz
 
App secforum2014 andrivet-cplusplus11-metaprogramming_applied_to_software_obf...
App secforum2014 andrivet-cplusplus11-metaprogramming_applied_to_software_obf...App secforum2014 andrivet-cplusplus11-metaprogramming_applied_to_software_obf...
App secforum2014 andrivet-cplusplus11-metaprogramming_applied_to_software_obf...Cyber Security Alliance
 
The Present and The Future of Functional Programming in C++
The Present and The Future of Functional Programming in C++The Present and The Future of Functional Programming in C++
The Present and The Future of Functional Programming in C++Alexander Granin
 
On the Necessity and Inapplicability of Python
On the Necessity and Inapplicability of PythonOn the Necessity and Inapplicability of Python
On the Necessity and Inapplicability of PythonTakeshi Akutsu
 
On the necessity and inapplicability of python
On the necessity and inapplicability of pythonOn the necessity and inapplicability of python
On the necessity and inapplicability of pythonYung-Yu Chen
 
Review chapter 1 2-3
Review chapter 1 2-3Review chapter 1 2-3
Review chapter 1 2-3ahmed22dg
 
CS-102 DS-class_01_02 Lectures Data .pdf
CS-102 DS-class_01_02 Lectures Data .pdfCS-102 DS-class_01_02 Lectures Data .pdf
CS-102 DS-class_01_02 Lectures Data .pdfssuser034ce1
 
ESL Anyone?
ESL Anyone? ESL Anyone?
ESL Anyone? DVClub
 
Big Data-Driven Applications with Cassandra and Spark
Big Data-Driven Applications  with Cassandra and SparkBig Data-Driven Applications  with Cassandra and Spark
Big Data-Driven Applications with Cassandra and SparkArtem Chebotko
 
Modern C++ Lunch and Learn
Modern C++ Lunch and LearnModern C++ Lunch and Learn
Modern C++ Lunch and LearnPaul Irwin
 
Python高级编程(二)
Python高级编程(二)Python高级编程(二)
Python高级编程(二)Qiangning Hong
 
Basic of c++ programming
Basic of c++ programmingBasic of c++ programming
Basic of c++ programmingTalha Mughal
 
25 лет истории C++, пролетевшей на моих глазах
25 лет истории C++, пролетевшей на моих глазах25 лет истории C++, пролетевшей на моих глазах
25 лет истории C++, пролетевшей на моих глазахcorehard_by
 
Kostiantyn Grygoriev "Wrapping C++ for Python"
Kostiantyn Grygoriev "Wrapping C++ for Python"Kostiantyn Grygoriev "Wrapping C++ for Python"
Kostiantyn Grygoriev "Wrapping C++ for Python"LogeekNightUkraine
 

Similar to C++: a fast tour of a fast language (20)

C++11 Was Only the Beginning
C++11 Was Only the BeginningC++11 Was Only the Beginning
C++11 Was Only the Beginning
 
Return of c++
Return of c++Return of c++
Return of c++
 
College1
College1College1
College1
 
Test Driven Interviewing in C++
Test Driven Interviewing in C++Test Driven Interviewing in C++
Test Driven Interviewing in C++
 
App secforum2014 andrivet-cplusplus11-metaprogramming_applied_to_software_obf...
App secforum2014 andrivet-cplusplus11-metaprogramming_applied_to_software_obf...App secforum2014 andrivet-cplusplus11-metaprogramming_applied_to_software_obf...
App secforum2014 andrivet-cplusplus11-metaprogramming_applied_to_software_obf...
 
The Present and The Future of Functional Programming in C++
The Present and The Future of Functional Programming in C++The Present and The Future of Functional Programming in C++
The Present and The Future of Functional Programming in C++
 
Beyond C++17
Beyond C++17Beyond C++17
Beyond C++17
 
On the Necessity and Inapplicability of Python
On the Necessity and Inapplicability of PythonOn the Necessity and Inapplicability of Python
On the Necessity and Inapplicability of Python
 
On the necessity and inapplicability of python
On the necessity and inapplicability of pythonOn the necessity and inapplicability of python
On the necessity and inapplicability of python
 
Review chapter 1 2-3
Review chapter 1 2-3Review chapter 1 2-3
Review chapter 1 2-3
 
CS-102 DS-class_01_02 Lectures Data .pdf
CS-102 DS-class_01_02 Lectures Data .pdfCS-102 DS-class_01_02 Lectures Data .pdf
CS-102 DS-class_01_02 Lectures Data .pdf
 
ESL Anyone?
ESL Anyone? ESL Anyone?
ESL Anyone?
 
Big Data-Driven Applications with Cassandra and Spark
Big Data-Driven Applications  with Cassandra and SparkBig Data-Driven Applications  with Cassandra and Spark
Big Data-Driven Applications with Cassandra and Spark
 
Modern C++ Lunch and Learn
Modern C++ Lunch and LearnModern C++ Lunch and Learn
Modern C++ Lunch and Learn
 
01_intro-cpp.ppt
01_intro-cpp.ppt01_intro-cpp.ppt
01_intro-cpp.ppt
 
01_intro-cpp.ppt
01_intro-cpp.ppt01_intro-cpp.ppt
01_intro-cpp.ppt
 
Python高级编程(二)
Python高级编程(二)Python高级编程(二)
Python高级编程(二)
 
Basic of c++ programming
Basic of c++ programmingBasic of c++ programming
Basic of c++ programming
 
25 лет истории C++, пролетевшей на моих глазах
25 лет истории C++, пролетевшей на моих глазах25 лет истории C++, пролетевшей на моих глазах
25 лет истории C++, пролетевшей на моих глазах
 
Kostiantyn Grygoriev "Wrapping C++ for Python"
Kostiantyn Grygoriev "Wrapping C++ for Python"Kostiantyn Grygoriev "Wrapping C++ for Python"
Kostiantyn Grygoriev "Wrapping C++ for Python"
 

Recently uploaded

Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 

Recently uploaded (20)

Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 

C++: a fast tour of a fast language

  • 1. C++: A FAST TOUR OF A FAST LANGUAGE ADRIAN OSTROWSKI 4DEVELOPERS, SEPTEMBER 25 , 2018TH
  • 2. • spent childhood in crop fields • 8 years in the software field, 6 years in C++ • west const propagator • interested in Agile, quality and performance • lifelong learner • music lover • gamer whoami 2
  • 3. What we will talk about today? • the fat and the gaunt years of C++ • why the language currently experiences its renaissance • what is Modern C++ and why you should care • how the language evolved and where will it go from here • how the ecosystem evolved along with the language What we won't talk about? • (too much) hard stuff • why C++ is "better" or "worse" than ${OTHER_LANG} AGENDA 3
  • 4. A PINCH OF HISTORY
  • 7. THE SAME NOW AS WHEN THE LANGUAGE WAS CREATED 1 There should be no language beneath C++ (except assembly) 2 You only pay for what you use 3 Offer high-level abstractions at low cost (strong aim for zero-cost) PHILOSOPHY OF C++ 7
  • 9. THE '90S - STL 9
  • 10. THE '90S - RISE OF OOP 10
  • 11. THE 2000S - COFFEE-BASED LANGUAGES 11
  • 12. SHIFT OF PRIORITIES • Battery life • Performance per watt • Low memory consumption • Retaining responsiveness MOBILE PLATFORMS 12
  • 13. SCALE CHANGES EVERYTHING • Low costs of software compared to total costs • Performance per watt • Optimizations scale through servers CLOUD PLATFORMS 13
  • 15. • performance (game development, high-frequency trading) • mission-critical systems, e.g. aeroplanes • OS development • automotive industry • blockchain • building blocks, e.g. for AI and ML WHERE ELSE IS C++ USED? 15
  • 16. HOW MUCH DOES C++ MATTER NOWADAYS? 16
  • 18. • C++11? WHAT IS MODERN C++? 18
  • 19. • C++11? • C++14? WHAT IS MODERN C++? 18
  • 20. • C++11? • C++14? • C++17? WHAT IS MODERN C++? 18
  • 21. • C++11? • C++14? • C++17? • Whatever the newest standard is? WHAT IS MODERN C++? 18
  • 22. • C++11? • C++14? • C++17? • Whatever the newest standard is? NOPE WHAT IS MODERN C++? 18
  • 23. • C++11? • C++14? • C++17? • Whatever the newest standard is? NOPE Modern C++ is not about the standard WHAT IS MODERN C++? 18
  • 24. • C++11? • C++14? • C++17? • Whatever the newest standard is? NOPE Modern C++ is not about the standard It's a philosophy of code design WHAT IS MODERN C++? 18
  • 25. • C++11? • C++14? • C++17? • Whatever the newest standard is? NOPE Modern C++ is not about the standard It's a philosophy of code design C++11 was heavily influenced by industry practices and popular libraries WHAT IS MODERN C++? 18
  • 26. Q: WHAT YEAR IS THIS BOOK FROM? 19
  • 27. Modern C++ isn't afraid of: • RAII SO HOW IT'S DIFFERENT THAN "OLD-STYLE" C++? 20
  • 28. Modern C++ isn't afraid of: • RAII • reuse of (standard) library components SO HOW IT'S DIFFERENT THAN "OLD-STYLE" C++? 20
  • 29. Modern C++ isn't afraid of: • RAII • reuse of (standard) library components • templates and metaprogramming SO HOW IT'S DIFFERENT THAN "OLD-STYLE" C++? 20
  • 30. Modern C++ isn't afraid of: • RAII • reuse of (standard) library components • templates and metaprogramming • mixing programming paradigms SO HOW IT'S DIFFERENT THAN "OLD-STYLE" C++? 20
  • 31. Have you ever leaked a resource? RESOURCE ACQUISITION IS INITIALIZATION 21
  • 32. Have you ever leaked a resource? Have you ever double-freed a resource? RESOURCE ACQUISITION IS INITIALIZATION 21
  • 33. Have you ever leaked a resource? Have you ever double-freed a resource? Had a hard time releasing them if an exception occurs? RESOURCE ACQUISITION IS INITIALIZATION 21
  • 34. Have you ever leaked a resource? Have you ever double-freed a resource? Had a hard time releasing them if an exception occurs? RAII takes the burden of resource handling from the programmer. RESOURCE ACQUISITION IS INITIALIZATION 21
  • 35. template<typename T> class SmartPtr : NonCopyable { public: explicit SmartPtr(T* ptr = nullptr) : ptr_{ptr} {} SmartPtr(const SmartPtr& other) = delete; SmartPtr& operator=(const SmartPtr& other) = delete; ~SmartPtr() { delete ptr_; } T& operator*() { return *ptr_; } const T& operator*() const { return *ptr_; } T* operator->() { return ptr_; } const T* operator->() const { return ptr_; } private: T* ptr_; }; RAII EXAMPLE: A SIMPLE SMART POINTER 22
  • 36. Who works in a company that has/had it's own string implementation? QUICK Q 23
  • 37. • generic programming • policy-based design • library reuse REUSE OF (STANDARD) LIBRARY COMPONENTS 24
  • 38. template<typename T, typename OverflowPolicy> class Treasury { public: void add(T amount) { if (OverflowPolicy::Check(treasure_, amount)) { treasure_ += amount; } } bool has_enough_value() { // TODO: become less greedy return false; } // ... private: T treasure_{}; }; POLICY-BASED DESIGN 25
  • 39. template<typename T> struct RobinHoodPolicy { bool Check(T& treasure, T amount) { auto space = std::numeric_limits<T>::max() - treasure_; if (space < amount) { Steal(amount - space); } return true; } }; using NottinghamTreasury = Treasury<int, RobinHoodPolicy<int>>; POLICY-BASED DESIGN, CONT'D 26
  • 40. Some great and free for commercial use libraries: • Boost • Abseil • EASTL • BDE/BSL • Folly REUSE EXISTING LIBRARIES 27
  • 41. Some great and free for commercial use libraries: • Boost • Abseil • EASTL • BDE/BSL • Folly Other libraries can be pulled by package managers like Conan. REUSE EXISTING LIBRARIES 27
  • 43. CMAKELISTS.TXT cmake_minimum_required(VERSION 3.12) project(my_precious) include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) conan_basic_setup(TARGETS) add_executable(my_precious src/main.cpp) target_compile_features(my_precious PUBLIC cxx_std_14) target_link_libraries(my_precious CONAN_PKG::range-v3) # also handles includes CONSOLE $ mkdir build && cd build $ conan install .. $ cmake .. -G "Visual Studio 15 Win64" CONAN, CONT'D 29
  • 44. template<int N> struct Factorial { static const int value = N * Factorial<N-1>::value; }; template<> struct Factorial<0> { static const int value = 1; }; int main() { std::cout << Factorial<12>::value << 'n'; } MODERN C++: TEMPLATES AND METAPROGRAMMING 30
  • 45. template<int N> struct Factorial { static const int value = N * Factorial<N-1>::value; }; template<> struct Factorial<0> { static const int value = 1; }; int main() { std::cout << Factorial<12>::value << 'n'; } C++ shifts more and more to compile-time computations MODERN C++: TEMPLATES AND METAPROGRAMMING 30
  • 46. constexpr int factorial(int n) { int result = n; while (n > 1) result *= --n; return result; } static_assert(factorial(4) == 24); int main() { std::cout << factorial(12) << 'n'; } CONSTEXPR FUNCTIONS 31
  • 47. constexpr int factorial(int n) { int result = n; while (n > 1) result *= --n; return result; } static_assert(factorial(4) == 24); int main() { std::cout << factorial(12) << 'n'; } Compile-time gets easier with newer standards CONSTEXPR FUNCTIONS 31
  • 48. Most use C++ as procedural/object-oriented, imperative language MODERN C++: MIXING PROGRAMMING PARADIGMS 32
  • 49. Most use C++ as procedural/object-oriented, imperative language It allows more than that. MODERN C++: MIXING PROGRAMMING PARADIGMS 32
  • 50. • templates • most of the standard library • auto keyword • template metaprogramming • constexpr functions GENERIC PROGRAMMING 33
  • 52. int main() { using namespace std::literals; using namespace ranges; auto is_even = [](int x) { return x % 2 != 0; }; auto to_string = [](int x) { return std::to_string(x); }; auto my_range = view::ints | view::filter(is_even) | view::drop(1) | view::take(3) | view::reverse | view::transform(to_string); std::cout << ranges::accumulate(my_range, ""s) << 'n'; } DECLARATIVE C++: RANGES V3 34
  • 53. // functions as 1st class citizens auto pow2 = [] (auto x) { return x*x; }; // higher order functions auto compose = [](auto f1, auto f2) { return [&] (auto ...params) { return f2(f1(std::forward<decltype(params)>(params)...)); }; }; std::cout << compose(std::plus<>{}, pow2)(2, 3); // prints 25 FUNCTIONAL C++ 35
  • 54. TO SUM UP, MODERN C++ RESULTS IN 36
  • 55. • safer and cleaner code TO SUM UP, MODERN C++ RESULTS IN 36
  • 56. • safer and cleaner code • which is faster to develop TO SUM UP, MODERN C++ RESULTS IN 36
  • 57. • safer and cleaner code • which is faster to develop • and faster at runtime! TO SUM UP, MODERN C++ RESULTS IN 36
  • 58. • safer and cleaner code • which is faster to develop • and faster at runtime! And it plays great with recent C++ standards TO SUM UP, MODERN C++ RESULTS IN 36
  • 60. LANGUAGE EVOLUTION THE GAME CHANGER - C++11
  • 61. • Passing ownership between objects using std::move std::unique_ptr<T> up(new T{}); std::unique_ptr<T> up2 = std::move(up); foo(std::move(up2)); MOVE SEMANTICS 39
  • 62. • Passing ownership between objects using std::move std::unique_ptr<T> up(new T{}); std::unique_ptr<T> up2 = std::move(up); foo(std::move(up2)); • Better performance by avoiding copies MOVE SEMANTICS 39
  • 63. • Passing ownership between objects using std::move std::unique_ptr<T> up(new T{}); std::unique_ptr<T> up2 = std::move(up); foo(std::move(up2)); • Better performance by avoiding copies • Moving creates an r-value reference, similarly to creating a new object MOVE SEMANTICS 39
  • 64. • Templates accepting arbitrary number of arguments, e.g. for creating tuples • Example: make_unique in C++11 template<class T, class... Args> inline std::unique_ptr<T> make_unique(Args&&... args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } VARIADIC TEMPLATES 40
  • 65. • Lightweight list of values • Can be used to construct containers in one go void foo(const std::vector<int> &v); auto numbers = { 1, 2, 3 }; // std::initializer_list<int> foo({numbers}); foo({3, 4, 5}); foo({}); std::map<int, std::string> my_map{ { 1, "one" }, { 2, "two" } }; INITIALIZER LISTS 41
  • 66. • Compile-time checks with simple error messages static_assert(sizeof(void *) * CHAR_BIT == 8, "64-bit platform required"); template <class T> T calculate(T x, T y) { static_assert(std::is_arithmetic<T>::value, "Can't calculate using non-numerical types"); // ... } STATIC ASSERTIONS 42
  • 67. • automatic type deduction for variables, return types, etc. • use it for correctness – avoid accidental type conversions • use if for generic programming – easier maintenance in case the used type changes • use it for readability - less is more • use it for safety – you can’t forget to initialize it // no changes when get_widget() returns unique_ptr instead of shared_ptr auto widget = get_widget(); auto it = map.find(42); // auto vs std::map<int, std::string>::iterator; auto func = [](int x) { return x * 2; }; auto KEYWORD 43
  • 68. • functions are now first class citizens • excellent for use with standard functions [](){ std::cout << "Hello Lambda World!n"; }; int x = 1; auto f1 = [&x] { return x *= 2; }; // modify original x auto f2 = [x] () mutable { return x *= 2; }; // modify copy std::vector<int> v{1, -2, 3}; std::sort(begin(v), end(v), [](int a, int b) { return b*b > a*a }); LAMBDA EXPRESSIONS 44
  • 69. std::vector<int> v{1, 2, 3, 4, 5}; for (int i: v) { std::cout << i << ' '; } for (int& i: v) { i *= 2; } RANGE-BASED FOR LOOPS 45
  • 70. • std::thread • std::atomic<T> • std::mutex and guards CONCURRENCY FACILITIES 46
  • 71. using namespace std::chrono; auto start = steady_clock::now(); // time_point<steady_clock> // insert measured work here auto end = steady_clock::now(); auto micros = duration_cast<microseconds>(end-start); // duration<long, std::micro> std::cout << micros.count() << 'n'; auto blink_of_an_eye = std::chrono::milliseconds(300); // more convenient since C++14 using namespace std::chrono::literals; auto day = 24h; std::chrono 47
  • 72. • std::array • std::unordered_map • std::unordered_set • std::tuple NEW CONTAINERS 48
  • 74. GENERIC LAMBDAS auto comparator = [](auto i, auto j) { return (i > j); }; auto ints = std::vector<int>{ 1, 12, 9, 10 }; std::sort(begin(ints), end(ints), comparator); auto strings = std::vector<std::string>{"cat", "dog", "ox", "aardvark"}; std::sort(begin(strings), end(strings), comparator); LAMBDA IMPROVEMENTS 50
  • 76. template<typename... Args> auto multiply(Args... args) { return (... * args); } void foo() { return multiply(1.f, 2.5, 4); } FOLD EXPRESSIONS 52
  • 77. // before template<int N> constexpr int fibonacci() {return fibonacci<N-1>() + fibonacci<N-2>(); } template<> constexpr int fibonacci<1>() { return 1; } template<> constexpr int fibonacci<0>() { return 0; } CONSTEXPR IF 53
  • 78. // before template<int N> constexpr int fibonacci() {return fibonacci<N-1>() + fibonacci<N-2>(); } template<> constexpr int fibonacci<1>() { return 1; } template<> constexpr int fibonacci<0>() { return 0; } // after template<int N> constexpr int fibonacci() { if constexpr (N>=2) return fibonacci<N-1>() + fibonacci<N-2>(); else return N; } CONSTEXPR IF 53
  • 79. // in some class std::vector v{1, 2, 3}; std::mutex mut; // in some function if (auto lock = std::scoped_lock{mut}; !v.empty()) { v.pop_back(); } IFS AND SWITCHES WITH INITIALIZERS 54
  • 80. // in some class std::vector v{1, 2, 3}; std::mutex mut; // in some function if (auto lock = std::scoped_lock{mut}; !v.empty()) { v.pop_back(); } switch (Command cmd = read_command(); cmd.type) { /* ... */} IFS AND SWITCHES WITH INITIALIZERS 54
  • 81. // in some class std::vector v{1, 2, 3}; std::mutex mut; // in some function if (auto lock = std::scoped_lock{mut}; !v.empty()) { v.pop_back(); } switch (Command cmd = read_command(); cmd.type) { /* ... */} if (auto [iter, success] = myset.insert("X"); success) {/* ... */} IFS AND SWITCHES WITH INITIALIZERS 54
  • 82. auto v = std::variant<int, string>{42}; std::get<int>(v); // returns 42 std::get<0>(v); // returns 42 std::get<double>(v); // compile-time error v = "not an int"; std::get<int>(v); // throws std::bad_variant_access STD::VARIANT - A TYPE-SAFE UNION 55
  • 83. using my_types = std::variant<int, std::string, double>; std::vector<my_types> vec{"XYZ", 1337, 21.37}; for(auto& v: vec) { v = std::visit([](auto&& arg) -> my_types { return arg + arg; }, v); } struct TypeNamingVisitor { void operator()(int&) { std::cout << "int"; } void operator()(std::string&) { std::cout << "string"; } void operator()(double&) { std::cout << "double"; } }; std::visit(TypeNamingVisitor{}, vec.front()); STD::VARIANT - VISITATION 56
  • 84. What can you tell about the following function? int* parse_number(const std::string& input); STD::OPTIONAL FOR CLEAN INTERFACES 57
  • 85. What can you tell about the following function? int* parse_number(const std::string& input); How about this one? int parse_number(const std::string& input); STD::OPTIONAL FOR CLEAN INTERFACES 57
  • 86. What can you tell about the following function? int* parse_number(const std::string& input); How about this one? int parse_number(const std::string& input); What about this one? std::optional<int> parse_number(const std::string& input); STD::OPTIONAL FOR CLEAN INTERFACES 57
  • 87. struct User { std::string name; std::string surname; std::optional<std::string> nickname; }; User{"Eldrick", "Woods", "Tiger"}; User{"John", "Smith", std::nullopt}; STD::OPTIONAL FOR CLEAN INTERFACES 58
  • 88. struct User { std::string name; std::string surname; std::optional<std::string> nickname; }; User{"Eldrick", "Woods", "Tiger"}; User{"John", "Smith", std::nullopt}; void login(const User& user, std::optional<year_month_day> passwordExpiration); STD::OPTIONAL FOR CLEAN INTERFACES 58
  • 89. // before void foo(const char *ptr); void foo(const char *ptr, size_t length); void foo(const std::string&); // after void foo(std::string_view); STD::STRING_VIEW 59
  • 90. Which is faster? Why? void foo(const std::string& str); foo("A quick brown fox jumps over the lazy dog"); // vs void bar(std::string_view); bar("A quick brown fox jumps over the lazy dog"); STD::STRING_VIEW 60
  • 91. Execution policies: • sequential (std::seq), • parallel (std::par), • parallel with vectorization (std::par_unseq). PARALLEL ALGORITHMS 61
  • 92. Execution policies: • sequential (std::seq), • parallel (std::par), • parallel with vectorization (std::par_unseq). USAGE std::algorithm_name(policy, usual_arguments...); PARALLEL ALGORITHMS 61
  • 93. • adjacent_{difference, find} • {all, any, none}_of • copy{, _if, _n} • count{, _if} • equal • fill{, _n} • find{, _end, _first_of, _if, _if_not} • generate{, _n} • includes • inner_product • inplace_merge PARALLEL ALGORITHMS - SUPPORTED EXISTING ALGOS • is_{heap, heap_until, partitioned, sorted, sorted_until} • lexicographical_compare • {max, min, minmax}_element • merge • mismatch • move • nth_element • partial_sort{, _copy} • partition{, _copy} • remove{, _copy, _if, _copy_if} • replace{, _copy, _if, _copy_if} • reverse{, _copy} • rotate{, _copy} • search{, _n} • set_{difference, intersection, symmetric_difference, union} • sort • stable_{partition, sort} • swap_ranges • transform • uninitialized_{copy, copy_n, fill, fill_n} • unique{, _copy} 62
  • 95. • type-checking in templates • simpler template error messages • easier selection of overloads and specializations • constraining automatic type deduction template<typename T> concept Hashable = requires(T a) { { std::hash<T>{}(a) } -> std::size_t; }; template<Hashable Key> auto get_bucket(Key key, std::size_t max_buckets) -> std::size_t; CONCEPTS - C++20 64
  • 96. std::list<int> l = {2, 1, 3}; std::sort(l.begin(), l.end()); In instantiation of 'void std::__sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = std::_List_iterator<int>; _Compare = __gnu_cxx::__ops::_Iter_less_iter]': error: no match for 'operator-' (operand types are 'std::_List_iterator<int>' and 'std::_List_iterator<int>') std::__lg(__last - __first) * 2, // few dozens more lines of error messages error: cannot call function 'void std::sort(_RAIter, _RAIter) [with _RAIter = std::_List_iterator<int>]' note: concept 'RandomAccessIterator()' was not satisfied CONCEPTS - ERROR MESSAGES 65
  • 97. void foo(const std::vector<int>& v) [[expects: !v.empty()]] [[ensures audit v2: is_sorted(v2)]] { int x = g(); [[assert: x > 0]] auto v2 = bar(v, x); return v2; } • Possible enforcing levels are: default, audit, and axiom CONTRACTS - C++20 66
  • 98. generator<int> even_numbers() { auto current = 0; while (true) { co_yield current; current += 2; } } COROUTINES - C++20/23 67
  • 99. generator<int> even_numbers() { auto current = 0; while (true) { co_yield current; current += 2; } } auto find_line(std::string resource, std::string key) -> std::future<std::expected<std::string>> { while (auto line = co_await fetch_line(co_await load(resource))) { if (contains(line, key)) co_return line; } co_return std::unexpected(not_found(resource)); } COROUTINES - C++20/23 67
  • 100. • Import a module instead of #including <files> • Much, much faster compile times • No more splitting code between header and cpp files • Easier package management MODULES - C++20/23 68
  • 101. • Generate classes of classes • Examples: interface, value, flag_enum, property, qt::signal & qt::slot constexpr void interface(meta::type target, const meta::type source) { compiler.require(source.variables().empty(), "interfaces can't contain data"); for (auto f : source.functions()) { if (!f.has_access()) f.make_public(); f.make_pure_virtual(); ->(target) f; } ->(target) { virtual ~(source.name()$)() noexcept {} } } interface Shape { string name() const; /*...*/ }; METACLASSES 69
  • 102. What problems did we have? • compiles were slow • compile errors were complicated • templates were hard to debug • memory leaks • no central place to go for news, papers etc. ECOSYSTEM EVOLUTION - CAUSES 70
  • 103. • Boost • CMake • Conan • Clang - for better developer productivity (faster compile times, better error messages, side effects: REPL, better GCC perf) • Sanitizers & Valgrind • Metashell • A plethora of blogs, books, conferences, online videos. ECOSYSTEM EVOLUTION - EFFECTS 71
  • 104. • Awesome C++ • isocpp.org • cppreference.com • Clang RESOURCES 72
  • 107. • Bjarne Stroustrup's photo by Julia Kryuchkova (edited), CC-BY-SA 2.5, Wikipedia • Bell Labs Holmdel Complex by Lee Beaumont, retouched by MBisanz & Kylu, CC-BY-SA 2.0, Wikipedia • Livraria do Senado by Senado Federal, CC-BY 2.0, Wikipedia • Microsoft Windows 95 screenshot, used with permission from Microsoft • Working lat(t)e by Kuba Bożanowski, CC-BY 2.0, Flickr • Alexander Stepanov's photo by Paul R. McJones, CC-BY-SA 3.0, Wikipedia • IEEE Spectrum Ranking • Tanks by Roger May, CC-BY-SA 2.0, Geograph.co.uk ATTRIBUTIONS 75