SlideShare a Scribd company logo
Modern C++ 
Lunch and Learn From an Amateur 
By Paul Irwin
Ancient History 
• C created by Dennis Ritchie, 1972 [9] 
• “C with Classes” created by Bjarne Stroustrup, 1979 
[9] 
• Renamed to C++, 1983 [9] 
• The C++ Programming Language, 1985 [9] 
• The C++ Programming Language 2nd Ed. and C++ 2.0, 
1989 [9] 
• ISO Standardization as C++98, 1998 [9] 
• Minor ISO revision in C++03, 2003 [9,4]
C++ is “C with Classes” 
• Often, C can be used in C++ [1] 
• C is fast, portable, and versatile [1] 
• Therefore so is C++ 
• C has only structs to define composite types 
• Passed by-value unless with a pointer 
• No inheritance, polymorphism, encapsulation 
• So not object-oriented 
• C++ adds classes that bring OO to C 
• But, knowing C is not a prerequisite for learning 
C++ [1]
C++ invalidates some C approaches 
• Macros are almost never necessary [1] 
• Don’t use malloc() [1] 
• Avoid void*, pointer arithmetic, unions, and casts 
[1] 
• Minimize use of arrays and C-style strings [1] 
• C does not provide a native Boolean type [2]
When Should I C++? 
• For Performance 
• Raw algorithms 
• C++/CLI code called from C# 
• For Interop 
• Got a native lib on your hands? Create a C++/CLI interop DLL. 
• For Portability 
• C++ can run on just about any device, any platform, any CPU 
that matters 
• For Resource Optimization 
• With nearly identical simple demo apps in C++ and C#, C++ used 
~90% less memory 
• Instant memory cleanup – all objects are “IDisposable“ [4] 
• Important for embedded devices, mobile, certain server 
applications
C-style Code 
Problems: 
• What if string is > 99 chars? 
• What if 0 is in middle of string? 
• What if char* is dangerous? 
• What if you forget to null-terminate?
C++ Standard Library std::string 
• Anytime you see “using namespace std” or “std::”, 
that is the C++ standard library 
• #include <string>
C++ Classes Primer 
C# developers go “HOLD ON A DAMN SECOND!” 
“Where’s the new keyword?”
Stack vs Heap 
• Person p(123, “Paul”); 
• Calls ctor Person(int id, string name) 
• Allocates on local function stack 
• No pointer! 
• Destroyed at end of scope – no memory management! – thanks “}” 
• Person* p = new Person(123, “Paul”); 
• Calls ctor Person(int id, string name) 
• Allocates on free heap space 
• Notice that little asterisk (grumble grumble) 
• Yes, it’s a damn pointer. 
• Not destroyed at end of scope – whoops, memory leak! 
• Remember: C++ does not have garbage collection! 
• We’ll come back to this…
.NET vs C++ 
• .NET Struct ~== C++ class on stack 
• C#: var kvp = new KeyValuePair<int, string>(123, “Paul”); 
• C++: KeyValuePair<int, string> kvp(123, “Paul”); 
• .NET Class ~== C++ class on heap 
• C#: Person p = new Person(123, “Paul”); 
• C++: Person* p = new Person(123, “Paul”); 
• .NET Interface ~== C++ … well … 
• Pure virtual functions (virtual void foo() = 0;) 
• Macros 
• Non-Virtual-Interfaces (NVI) 
• … and down the rabbit hole you go
Pointer Primer
C++ Templates Primer 
• vector<int> better than int[] 
• Looks like a generic type – kinda is, kinda isn’t 
• Created at compile time
C++/CLI Primer 
Notice: 
• CLR namespaces like C++ namespaces 
• ^ means CLR type 
• gcnew means allocate in CLR heap, 
garbage collected (hence “gc”) 
• C-style string to String^ 
• -> operator for dereference call: 
rx is a .NET reference type 
• :: scope operator for static 
instances/methods
C++/CLI Primer: Classes 
Notice: 
• ref keyword means CLR type 
• No need for Int32^ 
• property keyword for CLR properties 
• Mix-and-match C++/CLI and C++
Modern History 
• After C++03… 
• C++0x draft – expected to be released before 2010 
• C++0x -> C++11 – a wee bit late 
• First major release of C++ since C++98 – 13 years! 
• C++14 Working Draft 
• Minor release, 3 year cadence [4] 
• C++17 (expected) 
• Next major release, 3 year cadence [4]
C++11: move semantics 
• Prior to C++11, this code could 
result in a deep copy of v 
• v is created on the stack 
• We fill v with values 
• “return v” copies all values into v2 
when called – O(n) 
• C++11 now implicitly “moves” v 
into v2 
• Much better performance, esp. with 
large objects – O(1) 
• Further reading: std::move [3]
C++11: initializer lists 
• From previous slide, now we 
can do this instead 
• Calls ctor on vector<int> 
taking initializer_list<int> 
• You can return objects this 
way too [3] 
• Neat! But may still want ctors 
• You can write methods that 
take initializer_list<T> [3]
C++11: type inference 
• “var” spelled “auto” [4]
C++11: range-based for loop 
• Makes the previous slide look bad
C++11: lambda functions (!!!) 
• YAY 
So this clearly prints even numbers to the console. 
And actually, you really should be using range-based for here. 
But what’s up with that [] syntax?
C++11: lambda functions (cont’d) 
• [](int x) { return x + 1; } 
• Captures no closures [5] 
• [y](int x) { return x + y; } 
• Captures y by value (copy) [5] 
• [&](int x) { y += x; } 
• Capture any referenced variable (y here) by reference [5] 
• [=](int x) { return x + y; } 
• Capture any referenced variable (y here) by value (copy) [5] 
• [=, &y](int x) { y += x + z; } 
• Capture any referenced variable (z here) by value (copy); but capture 
y by reference [5] 
• [this](int x) { return x + _privateFieldY; } 
• Capture the “this” pointer in the scope of the lambda [5]
C++11: lambda functions (cont’d)
C++11: strongly typed enums 
• In C++03, enums are not type safe [6] 
• C++11 adds “enum class” for type safety [3]
C++11: std::thread
C++11: std::tuple
C++11: std::regex
C++11: shared_ptr, unique_ptr 
• Consider: Person* GetPerson() { … } 
• What should be done with the results? [7] 
• Who owns the pointer? 
• If I “delete” it, what will happen downstream? 
• Enter std::shared_ptr and std::unique_ptr [7] 
• shared_ptr: reference-counted ownership of pointer 
• unique_ptr: only one unique_ptr object can own at a given 
time 
• unique_ptr deprecates auto_ptr
C++11: std::make_shared 
• Forwards arguments to constructor parameters 
Notice: 
• Return types and parameter types 
are explicit and clear 
• -> still used like with raw 
pointers 
• NO DAMN ASTERISKS! 
• When DealWithPersons’ scope ends 
(“}”), no more references, so 
pointer is cleaned up 
automatically 
• Could also call “return 
shared_ptr<Person>(new 
Person(…))” in MakePerson
C++14: std::make_unique 
• Oops! std::make_unique was not in the C++11 standard. 
• Same usage as make_shared, supported in VS2013
C++14: return type deduction
C++14: binary literals 
• 0b10010010 
• Also coming to C#!
C++14: generic lambdas 
• Use auto to make a generic lambda [8]
C++17?: pattern matching 
int eval(Expr& e) // expression evaluator 
{ 
Expr* a,*b; 
int n; 
match (e) 
{ 
case (C<Value>(n)): return n; 
case (C<Plus>(a,b)): return eval(*a) + eval(*b); 
case (C<Minus>(a,b)): return eval(*a) - eval(*b); 
case (C<Times>(a,b)): return eval(*a) * eval(*b); 
case (C<Divide>(a,b)): return eval(*a) / eval(*b); 
} 
} 
// From [10], possible syntax mine (not indicative of any proposed syntax I’ve seen)
C++17?: async/await 
future<void> f(stream str) async 
{ 
shared_ptr<vector> buf = ...; 
int count = await str.read(512, buf); 
return count + 11; 
} 
future g() async 
{ 
stream s = ...; 
int pls11 = await f(s); 
s.close(); 
} 
// Code from [11] 
Notice: 
• future<T> equivalent to Task<T> 
• async/await very similar to C# 
• std::future already in the 
standard since C++11!
C++17?: modules 
// File_1.cpp: 
export Lib: 
import std; 
using namespace std; 
public: 
namespace N { 
struct S { 
S() { 
cout << “S()n”; 
} 
}; 
} 
// File_2.cpp: 
import Lib; // no guard needed 
int main() { 
N::S s; 
} 
// Code modified from [12]
References 
1. The C++ Programming Language, Special Edition, B. Stroustrup, 1997 
2. Differences Between C and C++, http://www.cprogramming.com/tutorial/c-vs-c++.html 
3. C++11, http://en.wikipedia.org/wiki/C%2B%2B11 
4. Modern C++: What You Need To Know [Video], http://channel9.msdn.com/Events/Build/2014/2-661 
5. C++11 – Lambda Closures, The Definitive Guide, http://www.cprogramming.com/c++11/c++11- 
lambda-closures.html 
6. C++ Enumeration Declarations, http://msdn.microsoft.com/en-us/library/2dzy4k6e.aspx 
7. Smart Pointers, http://en.wikipedia.org/wiki/Smart_pointer 
8. C++14, http://en.wikipedia.org/wiki/C%2B%2B14 
9. C++, http://en.wikipedia.org/wiki/C%2B%2B 
10. C++14 and early thoughts about C++17 [Slides PDF], B. Stroutstrup, 
https://parasol.tamu.edu/people/bs/622-GP/C++14TAMU.pdf 
11. Resumable Functions – Async and await – Meeting C++, 
http://meetingcpp.com/index.php/br/items/resumable-functions-async-and-await.html 
12. Modules in C++, D. Vandevoorde, http://www.open-std. 
org/jtc1/sc22/wg21/docs/papers/2007/n2316.pdf

More Related Content

What's hot

C++20 the small things - Timur Doumler
C++20 the small things - Timur DoumlerC++20 the small things - Timur Doumler
C++20 the small things - Timur Doumlercorehard_by
 
Garbage Collection
Garbage CollectionGarbage Collection
Garbage CollectionEelco Visser
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4Abed Bukhari
 
Unmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/InvokeUnmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/InvokeDmitri Nesteruk
 
Why my Go program is slow?
Why my Go program is slow?Why my Go program is slow?
Why my Go program is slow?Inada Naoki
 
How to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITHow to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITEgor Bogatov
 
maXbox Starter 39 GEO Maps Tutorial
maXbox Starter 39 GEO Maps TutorialmaXbox Starter 39 GEO Maps Tutorial
maXbox Starter 39 GEO Maps TutorialMax Kleiner
 
C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012 C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012 Sumant Tambe
 
Basic c++ programs
Basic c++ programsBasic c++ programs
Basic c++ programsharman kaur
 
Javascript engine performance
Javascript engine performanceJavascript engine performance
Javascript engine performanceDuoyi Wu
 
Yampa AFRP Introduction
Yampa AFRP IntroductionYampa AFRP Introduction
Yampa AFRP IntroductionChengHui Weng
 
Virtual machine and javascript engine
Virtual machine and javascript engineVirtual machine and javascript engine
Virtual machine and javascript engineDuoyi Wu
 
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...Sergey Platonov
 
High performance web programming with C++14
High performance web programming with C++14High performance web programming with C++14
High performance web programming with C++14Matthieu Garrigues
 

What's hot (20)

C++20 the small things - Timur Doumler
C++20 the small things - Timur DoumlerC++20 the small things - Timur Doumler
C++20 the small things - Timur Doumler
 
Garbage Collection
Garbage CollectionGarbage Collection
Garbage Collection
 
Rcpp11 useR2014
Rcpp11 useR2014Rcpp11 useR2014
Rcpp11 useR2014
 
C++11
C++11C++11
C++11
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
 
Unmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/InvokeUnmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/Invoke
 
Why my Go program is slow?
Why my Go program is slow?Why my Go program is slow?
Why my Go program is slow?
 
C++ via C#
C++ via C#C++ via C#
C++ via C#
 
How to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITHow to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJIT
 
maXbox Starter 39 GEO Maps Tutorial
maXbox Starter 39 GEO Maps TutorialmaXbox Starter 39 GEO Maps Tutorial
maXbox Starter 39 GEO Maps Tutorial
 
C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012 C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012
 
Brief Introduction to Cython
Brief Introduction to CythonBrief Introduction to Cython
Brief Introduction to Cython
 
Basic c++ programs
Basic c++ programsBasic c++ programs
Basic c++ programs
 
Blazing Fast Windows 8 Apps using Visual C++
Blazing Fast Windows 8 Apps using Visual C++Blazing Fast Windows 8 Apps using Visual C++
Blazing Fast Windows 8 Apps using Visual C++
 
Javascript engine performance
Javascript engine performanceJavascript engine performance
Javascript engine performance
 
Yampa AFRP Introduction
Yampa AFRP IntroductionYampa AFRP Introduction
Yampa AFRP Introduction
 
Virtual machine and javascript engine
Virtual machine and javascript engineVirtual machine and javascript engine
Virtual machine and javascript engine
 
R/C++ talk at earl 2014
R/C++ talk at earl 2014R/C++ talk at earl 2014
R/C++ talk at earl 2014
 
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
 
High performance web programming with C++14
High performance web programming with C++14High performance web programming with C++14
High performance web programming with C++14
 

Viewers also liked

Metaprogramming in C++ - from 70's to C++17
Metaprogramming in C++ - from 70's to C++17Metaprogramming in C++ - from 70's to C++17
Metaprogramming in C++ - from 70's to C++17Sławomir Zborowski
 
Regular types in C++
Regular types in C++Regular types in C++
Regular types in C++Ilio Catallo
 
C++17 - the upcoming revolution (Code::Dive 2015)/
C++17 - the upcoming revolution (Code::Dive 2015)/C++17 - the upcoming revolution (Code::Dive 2015)/
C++17 - the upcoming revolution (Code::Dive 2015)/Sławomir Zborowski
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and BeyondComicSansMS
 
How to upload to slideshare and embed in blogger
How to upload to slideshare and embed in bloggerHow to upload to slideshare and embed in blogger
How to upload to slideshare and embed in bloggerDaybird1987
 
C++のライブラリを簡単に眺めてみよう
C++のライブラリを簡単に眺めてみようC++のライブラリを簡単に眺めてみよう
C++のライブラリを簡単に眺めてみようHiro H.
 

Viewers also liked (7)

Presentation
PresentationPresentation
Presentation
 
Metaprogramming in C++ - from 70's to C++17
Metaprogramming in C++ - from 70's to C++17Metaprogramming in C++ - from 70's to C++17
Metaprogramming in C++ - from 70's to C++17
 
Regular types in C++
Regular types in C++Regular types in C++
Regular types in C++
 
C++17 - the upcoming revolution (Code::Dive 2015)/
C++17 - the upcoming revolution (Code::Dive 2015)/C++17 - the upcoming revolution (Code::Dive 2015)/
C++17 - the upcoming revolution (Code::Dive 2015)/
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and Beyond
 
How to upload to slideshare and embed in blogger
How to upload to slideshare and embed in bloggerHow to upload to slideshare and embed in blogger
How to upload to slideshare and embed in blogger
 
C++のライブラリを簡単に眺めてみよう
C++のライブラリを簡単に眺めてみようC++のライブラリを簡単に眺めてみよう
C++のライブラリを簡単に眺めてみよう
 

Similar to Modern C++ Lunch and Learn

C++ process new
C++ process newC++ process new
C++ process new敬倫 林
 
Presentation on C++ Programming Language
Presentation on C++ Programming LanguagePresentation on C++ Programming Language
Presentation on C++ Programming Languagesatvirsandhu9
 
Cs1123 11 pointers
Cs1123 11 pointersCs1123 11 pointers
Cs1123 11 pointersTAlha MAlik
 
C++ programming intro
C++ programming introC++ programming intro
C++ programming intromarklaloo
 
Fundamentals of Programming in C++.ppt
Fundamentals of Programming in C++.pptFundamentals of Programming in C++.ppt
Fundamentals of Programming in C++.pptAamirShahzad527024
 
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
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...GeeksLab Odessa
 
2 BytesC++ course_2014_c1_basicsc++
2 BytesC++ course_2014_c1_basicsc++2 BytesC++ course_2014_c1_basicsc++
2 BytesC++ course_2014_c1_basicsc++kinan keshkeh
 
Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)Brendan Eich
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overviewTAlha MAlik
 
C to C++ Migration Strategy
C to C++ Migration Strategy C to C++ Migration Strategy
C to C++ Migration Strategy Colin Walls
 
c programming L-1.pdf43333333544444444444444444444
c programming L-1.pdf43333333544444444444444444444c programming L-1.pdf43333333544444444444444444444
c programming L-1.pdf43333333544444444444444444444PurvaShyama
 
Introduction to C#
Introduction to C#Introduction to C#
Introduction to C#ANURAG SINGH
 
Learning C++ - Introduction to c++ programming 1
Learning C++ - Introduction to c++ programming 1Learning C++ - Introduction to c++ programming 1
Learning C++ - Introduction to c++ programming 1Ali Aminian
 
c++-language-1208539706757125-9.pdf
c++-language-1208539706757125-9.pdfc++-language-1208539706757125-9.pdf
c++-language-1208539706757125-9.pdfnisarmca
 

Similar to Modern C++ Lunch and Learn (20)

Return of c++
Return of c++Return of c++
Return of c++
 
C++ process new
C++ process newC++ process new
C++ process new
 
Presentation on C++ Programming Language
Presentation on C++ Programming LanguagePresentation on C++ Programming Language
Presentation on C++ Programming Language
 
Cs1123 11 pointers
Cs1123 11 pointersCs1123 11 pointers
Cs1123 11 pointers
 
C++ programming intro
C++ programming introC++ programming intro
C++ programming intro
 
L6
L6L6
L6
 
Lecture1
Lecture1Lecture1
Lecture1
 
Fundamentals of Programming in C++.ppt
Fundamentals of Programming in C++.pptFundamentals of Programming in C++.ppt
Fundamentals of Programming in C++.ppt
 
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...
 
Modern C++
Modern C++Modern C++
Modern C++
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
 
2 BytesC++ course_2014_c1_basicsc++
2 BytesC++ course_2014_c1_basicsc++2 BytesC++ course_2014_c1_basicsc++
2 BytesC++ course_2014_c1_basicsc++
 
Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
 
C to C++ Migration Strategy
C to C++ Migration Strategy C to C++ Migration Strategy
C to C++ Migration Strategy
 
c programming L-1.pdf43333333544444444444444444444
c programming L-1.pdf43333333544444444444444444444c programming L-1.pdf43333333544444444444444444444
c programming L-1.pdf43333333544444444444444444444
 
Introduction to C#
Introduction to C#Introduction to C#
Introduction to C#
 
Learning C++ - Introduction to c++ programming 1
Learning C++ - Introduction to c++ programming 1Learning C++ - Introduction to c++ programming 1
Learning C++ - Introduction to c++ programming 1
 
Basics of objective c
Basics of objective cBasics of objective c
Basics of objective c
 
c++-language-1208539706757125-9.pdf
c++-language-1208539706757125-9.pdfc++-language-1208539706757125-9.pdf
c++-language-1208539706757125-9.pdf
 

Recently uploaded

A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1KnowledgeSeed
 
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...rajkumar669520
 
AI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in MichelangeloAI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in MichelangeloAlluxio, Inc.
 
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
 
Agnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in KrakówAgnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in Krakówbim.edu.pl
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILNatan Silnitsky
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyanic lab
 
Crafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM IntegrationCrafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM IntegrationWave PLM
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke
 
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 ServicesKrzysztofKkol1
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Anthony Dahanne
 
Studiovity film pre-production and screenwriting software
Studiovity film pre-production and screenwriting softwareStudiovity film pre-production and screenwriting software
Studiovity film pre-production and screenwriting softwareinfo611746
 
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdfA Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdfkalichargn70th171
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...Alluxio, Inc.
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?XfilesPro
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessWSO2
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2
 
Breaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdfBreaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdfMeon Technology
 

Recently uploaded (20)

A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
 
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
 
AI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in MichelangeloAI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in Michelangelo
 
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...
 
Agnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in KrakówAgnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in Kraków
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
Crafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM IntegrationCrafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM Integration
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
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
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
Studiovity film pre-production and screenwriting software
Studiovity film pre-production and screenwriting softwareStudiovity film pre-production and screenwriting software
Studiovity film pre-production and screenwriting software
 
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdfA Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Breaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdfBreaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdf
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 

Modern C++ Lunch and Learn

  • 1. Modern C++ Lunch and Learn From an Amateur By Paul Irwin
  • 2. Ancient History • C created by Dennis Ritchie, 1972 [9] • “C with Classes” created by Bjarne Stroustrup, 1979 [9] • Renamed to C++, 1983 [9] • The C++ Programming Language, 1985 [9] • The C++ Programming Language 2nd Ed. and C++ 2.0, 1989 [9] • ISO Standardization as C++98, 1998 [9] • Minor ISO revision in C++03, 2003 [9,4]
  • 3. C++ is “C with Classes” • Often, C can be used in C++ [1] • C is fast, portable, and versatile [1] • Therefore so is C++ • C has only structs to define composite types • Passed by-value unless with a pointer • No inheritance, polymorphism, encapsulation • So not object-oriented • C++ adds classes that bring OO to C • But, knowing C is not a prerequisite for learning C++ [1]
  • 4. C++ invalidates some C approaches • Macros are almost never necessary [1] • Don’t use malloc() [1] • Avoid void*, pointer arithmetic, unions, and casts [1] • Minimize use of arrays and C-style strings [1] • C does not provide a native Boolean type [2]
  • 5. When Should I C++? • For Performance • Raw algorithms • C++/CLI code called from C# • For Interop • Got a native lib on your hands? Create a C++/CLI interop DLL. • For Portability • C++ can run on just about any device, any platform, any CPU that matters • For Resource Optimization • With nearly identical simple demo apps in C++ and C#, C++ used ~90% less memory • Instant memory cleanup – all objects are “IDisposable“ [4] • Important for embedded devices, mobile, certain server applications
  • 6. C-style Code Problems: • What if string is > 99 chars? • What if 0 is in middle of string? • What if char* is dangerous? • What if you forget to null-terminate?
  • 7. C++ Standard Library std::string • Anytime you see “using namespace std” or “std::”, that is the C++ standard library • #include <string>
  • 8. C++ Classes Primer C# developers go “HOLD ON A DAMN SECOND!” “Where’s the new keyword?”
  • 9. Stack vs Heap • Person p(123, “Paul”); • Calls ctor Person(int id, string name) • Allocates on local function stack • No pointer! • Destroyed at end of scope – no memory management! – thanks “}” • Person* p = new Person(123, “Paul”); • Calls ctor Person(int id, string name) • Allocates on free heap space • Notice that little asterisk (grumble grumble) • Yes, it’s a damn pointer. • Not destroyed at end of scope – whoops, memory leak! • Remember: C++ does not have garbage collection! • We’ll come back to this…
  • 10. .NET vs C++ • .NET Struct ~== C++ class on stack • C#: var kvp = new KeyValuePair<int, string>(123, “Paul”); • C++: KeyValuePair<int, string> kvp(123, “Paul”); • .NET Class ~== C++ class on heap • C#: Person p = new Person(123, “Paul”); • C++: Person* p = new Person(123, “Paul”); • .NET Interface ~== C++ … well … • Pure virtual functions (virtual void foo() = 0;) • Macros • Non-Virtual-Interfaces (NVI) • … and down the rabbit hole you go
  • 12. C++ Templates Primer • vector<int> better than int[] • Looks like a generic type – kinda is, kinda isn’t • Created at compile time
  • 13. C++/CLI Primer Notice: • CLR namespaces like C++ namespaces • ^ means CLR type • gcnew means allocate in CLR heap, garbage collected (hence “gc”) • C-style string to String^ • -> operator for dereference call: rx is a .NET reference type • :: scope operator for static instances/methods
  • 14. C++/CLI Primer: Classes Notice: • ref keyword means CLR type • No need for Int32^ • property keyword for CLR properties • Mix-and-match C++/CLI and C++
  • 15. Modern History • After C++03… • C++0x draft – expected to be released before 2010 • C++0x -> C++11 – a wee bit late • First major release of C++ since C++98 – 13 years! • C++14 Working Draft • Minor release, 3 year cadence [4] • C++17 (expected) • Next major release, 3 year cadence [4]
  • 16. C++11: move semantics • Prior to C++11, this code could result in a deep copy of v • v is created on the stack • We fill v with values • “return v” copies all values into v2 when called – O(n) • C++11 now implicitly “moves” v into v2 • Much better performance, esp. with large objects – O(1) • Further reading: std::move [3]
  • 17. C++11: initializer lists • From previous slide, now we can do this instead • Calls ctor on vector<int> taking initializer_list<int> • You can return objects this way too [3] • Neat! But may still want ctors • You can write methods that take initializer_list<T> [3]
  • 18. C++11: type inference • “var” spelled “auto” [4]
  • 19. C++11: range-based for loop • Makes the previous slide look bad
  • 20. C++11: lambda functions (!!!) • YAY So this clearly prints even numbers to the console. And actually, you really should be using range-based for here. But what’s up with that [] syntax?
  • 21. C++11: lambda functions (cont’d) • [](int x) { return x + 1; } • Captures no closures [5] • [y](int x) { return x + y; } • Captures y by value (copy) [5] • [&](int x) { y += x; } • Capture any referenced variable (y here) by reference [5] • [=](int x) { return x + y; } • Capture any referenced variable (y here) by value (copy) [5] • [=, &y](int x) { y += x + z; } • Capture any referenced variable (z here) by value (copy); but capture y by reference [5] • [this](int x) { return x + _privateFieldY; } • Capture the “this” pointer in the scope of the lambda [5]
  • 23. C++11: strongly typed enums • In C++03, enums are not type safe [6] • C++11 adds “enum class” for type safety [3]
  • 27. C++11: shared_ptr, unique_ptr • Consider: Person* GetPerson() { … } • What should be done with the results? [7] • Who owns the pointer? • If I “delete” it, what will happen downstream? • Enter std::shared_ptr and std::unique_ptr [7] • shared_ptr: reference-counted ownership of pointer • unique_ptr: only one unique_ptr object can own at a given time • unique_ptr deprecates auto_ptr
  • 28. C++11: std::make_shared • Forwards arguments to constructor parameters Notice: • Return types and parameter types are explicit and clear • -> still used like with raw pointers • NO DAMN ASTERISKS! • When DealWithPersons’ scope ends (“}”), no more references, so pointer is cleaned up automatically • Could also call “return shared_ptr<Person>(new Person(…))” in MakePerson
  • 29. C++14: std::make_unique • Oops! std::make_unique was not in the C++11 standard. • Same usage as make_shared, supported in VS2013
  • 30. C++14: return type deduction
  • 31. C++14: binary literals • 0b10010010 • Also coming to C#!
  • 32. C++14: generic lambdas • Use auto to make a generic lambda [8]
  • 33. C++17?: pattern matching int eval(Expr& e) // expression evaluator { Expr* a,*b; int n; match (e) { case (C<Value>(n)): return n; case (C<Plus>(a,b)): return eval(*a) + eval(*b); case (C<Minus>(a,b)): return eval(*a) - eval(*b); case (C<Times>(a,b)): return eval(*a) * eval(*b); case (C<Divide>(a,b)): return eval(*a) / eval(*b); } } // From [10], possible syntax mine (not indicative of any proposed syntax I’ve seen)
  • 34. C++17?: async/await future<void> f(stream str) async { shared_ptr<vector> buf = ...; int count = await str.read(512, buf); return count + 11; } future g() async { stream s = ...; int pls11 = await f(s); s.close(); } // Code from [11] Notice: • future<T> equivalent to Task<T> • async/await very similar to C# • std::future already in the standard since C++11!
  • 35. C++17?: modules // File_1.cpp: export Lib: import std; using namespace std; public: namespace N { struct S { S() { cout << “S()n”; } }; } // File_2.cpp: import Lib; // no guard needed int main() { N::S s; } // Code modified from [12]
  • 36. References 1. The C++ Programming Language, Special Edition, B. Stroustrup, 1997 2. Differences Between C and C++, http://www.cprogramming.com/tutorial/c-vs-c++.html 3. C++11, http://en.wikipedia.org/wiki/C%2B%2B11 4. Modern C++: What You Need To Know [Video], http://channel9.msdn.com/Events/Build/2014/2-661 5. C++11 – Lambda Closures, The Definitive Guide, http://www.cprogramming.com/c++11/c++11- lambda-closures.html 6. C++ Enumeration Declarations, http://msdn.microsoft.com/en-us/library/2dzy4k6e.aspx 7. Smart Pointers, http://en.wikipedia.org/wiki/Smart_pointer 8. C++14, http://en.wikipedia.org/wiki/C%2B%2B14 9. C++, http://en.wikipedia.org/wiki/C%2B%2B 10. C++14 and early thoughts about C++17 [Slides PDF], B. Stroutstrup, https://parasol.tamu.edu/people/bs/622-GP/C++14TAMU.pdf 11. Resumable Functions – Async and await – Meeting C++, http://meetingcpp.com/index.php/br/items/resumable-functions-async-and-await.html 12. Modules in C++, D. Vandevoorde, http://www.open-std. org/jtc1/sc22/wg21/docs/papers/2007/n2316.pdf