SlideShare une entreprise Scribd logo
1  sur  36
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

Contenu connexe

Tendances

Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
Abed Bukhari
 
Unmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/InvokeUnmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/Invoke
Dmitri Nesteruk
 
Javascript engine performance
Javascript engine performanceJavascript engine performance
Javascript engine performance
Duoyi Wu
 

Tendances (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
 

En vedette

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
Daybird1987
 

En vedette (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++のライブラリを簡単に眺めてみよう
 

Similaire à Modern C++ Lunch and Learn

Cs1123 11 pointers
Cs1123 11 pointersCs1123 11 pointers
Cs1123 11 pointers
TAlha MAlik
 
C++ programming intro
C++ programming introC++ programming intro
C++ programming intro
marklaloo
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
TAlha MAlik
 
c programming L-1.pdf43333333544444444444444444444
c programming L-1.pdf43333333544444444444444444444c programming L-1.pdf43333333544444444444444444444
c programming L-1.pdf43333333544444444444444444444
PurvaShyama
 
c++-language-1208539706757125-9.pdf
c++-language-1208539706757125-9.pdfc++-language-1208539706757125-9.pdf
c++-language-1208539706757125-9.pdf
nisarmca
 

Similaire à 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
 

Dernier

%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 

Dernier (20)

%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
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...
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
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
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 

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