SlideShare a Scribd company logo
Gentle* Introduction to
Modern C++
Mihai Todor
* Well, maybe not so gentle 
Disclaimer: This presentation is focused on C++11 features and assumes a basic understanding of C++
Intro I
 C++ is boring / hard to get right
 The C++ compilers are buggy
 We don’t want to mess with it
Intro II
And your code looks like this*:
*That’s actually C# code, but you get the point 
Intro III
WRONG MENTALITY!
Intro IV
In spite of the fact that it lacks some of
the C# flexibility and compactness,
C++ is a beautiful language, having a
rich syntax, which enables a high
degree of expressivity and abstraction,
with a fine grained control over
resource consumption.
Intro V
 If done right, in C++ you only pay for
what you use
 If done wrong, in C++ you blow your
entire leg off, not just a toe
Intro VI
 The compiler is never* wrong
 C++11 features alleviate much of the
pain we had to endure when
architecting code
 The STL is becoming richer and more
flexible
 Compilers are adopting new features
much faster
*well, maybe sometimes, but it usually requires more than 10 minutes of coding to stumble upon a legit compiler bug
Some modern C++ features
 Move semantics
 Auto
 nullptr
 Range-based for loops
 override and final
 Strongly-typed enums
 Lambdas
 Explicitly defaulted and deleted functions
 Smart pointers
Move semantics
 Copies are expensive!
 Want speed, pass by value (not always*)
 Moving variables can be as cheap as a
pointer swap
 Classes can now have move constructors
and move assignment operators
* http://juanchopanzacpp.wordpress.com/2014/05/11/want-speed-dont-always-pass-by-value/
Move semantics II
 In C++11, an expression can be:
The && operator has been introduced in order to declare an rvalue reference
Diagram shamelessly ripped from here: http://stackoverflow.com/a/3601748/1174378
Move semantics III
 xvalue (an “eXpiring” value) – also refers to
an object, usually near the end of its lifetime
 A type Type followed by && represents an rvalue
reference
 xvalues are explicit moves, created by std::move
 prvalue (“pure” rvalue) - an rvalue that is not
an xvalue (implicit moves)
Move semantics IV
 A reference type that is declared using
& is called an lvalue reference
 A reference type that is declared using
&& is called an rvalue reference.
Move semantics V
 Powerful tools in the <utility> header:
 std::move
 std::forward
 std::make_move_iterator
A thorough explanation for std::move and std::forward:
http://blogs.msdn.com/b/vcblog/archive/2009/02/03/rvalue-references-c-0x-features-in-vc10-part-2.aspx
auto
 Repurposed keyword (initially, it designated a
storage duration specifier)
 Similar to C#’s var keyword
 Reduces code verbosity by deducing a variable’s
type from the initializer
 Also allows return type deduction (C++14)
 Potential for abuse!
nullptr
 Eliminates the ambiguous conversion between NULL
(#defined as 0) and integral types
 Denotes a value of type std::nullptr_t
 Converts implicitly to bool (as false) and null pointer values of
any type
 You don’t have to test a variable for null with both NULL and
nullptr!
int *pointer = LegacyGetInt();
if (pointer != nullptr && pointer != NULL)//both tests are equivalent
Range-based for loops
 They resemble the C# foreach statement
 Syntax: for (auto value: collection) {/* do stuff */}
 the type specifier of value determines how the collection
items are iterated: by value, by reference, by const
reference, etc
 Can be used with any type for which non-member
overloads of the begin() and end() functions are
implemented
 see NonMemberBeginAndEnd.cpp
override and final
 If override is added to the declaration of a virtual
method, which does not override a virtual method
from the base class, the compiler emits an error
 If final is added to the declaration of a virtual
method, then derived classes are not allowed to
override this method
 in C++, the virtual specifier is optional for derived class
override methods
 If final is added to the declaration of a class, then
no other classes can derive from that class. This
resembles C#’s sealed keyword
Strongly-typed enums
 Eliminate issues caused by regular enums: namespace
pollution and implicit conversions
 For now, there is no simple way to use these in the same way
as a C# flags enum (tagged enumeration)
 The enum class underlying type can be specified by the user:
enum class Colors : std::int8_t { RED = 1, GREEN = 2, BLUE = 3 };
 Extracting underlying values of an enum class requires an
explicit cast:
auto blue = static_cast<std::underlying_type<Colors>::type>(Colors::Blue);
Smart pointers
 They provide reference counting in order to enable the automatic
release of memory
 Concerns about performance degradation / extra memory
consumption are, indeed, legitimate, but in most cases we are not
creating millions of objects on the heap to have really tight
constraints
 std::unique_ptr – Guarantees unique ownership of a memory
resource. It cannot be copied (only moved to another
std::unique_ptr).
 Created with std::make_unique (C++14)
 std::auto_ptr is obsolete! Please replace it on sight with
std::unique_ptr.
Smart pointers II
 std::shared_ptr – Allows shared ownership of a
memory resource
 Created with std::make_shared (C++11)
 std::weak_ptr – Holds a reference to an object
managed by an std::shared_ptr.
 does not contribute to the reference count
 Ensures that cycles are broken
 std::static_pointer_cast, std::dynamic_pointer_cast
and std::const_pointer_cast are your friends!
Lambdas
 C++11 introduces support for anonymous
functions, namely lambdas
 Fine-grained control over variable capture
 By default, variables captured by value are
const, unless the mutable specification is
present
 We can have recursive lambdas
Lambdas II
 Syntax (shamelessly ripped from MSDN*)
1. lambda-introducer (Also known as the capture clause)
2. lambda declarator (Also known as the parameter list).
Optional!
3. mutable (Also known as the mutable specification) .
Optional!
4. exception-specification (Also known as the exception
specification) . Optional!
5. trailing-return-type (Also known as the return type) .
Optional!
6. compound-statement (Also known as the lambda body)
* http://msdn.microsoft.com/en-us/library/dd293603.aspx
Explicitly defaulted and
deleted functions
 The rules which specify when the implicitly-
declared default constructor and destructor,
copy and move constructors and copy and
move assignment operators get generated
are somewhat complex, so C++11 allows
you to force the compiler to generate them
or not, via the =default and =delete
specifiers.
 Please take the Rules of three/five/zero into
account when using these specifiers!
Explicitly defaulted and
deleted functions II
 Let’s design a trivial object, which can be
constructed and moved, but not copied
class UniqueObject
{
public:
UniqueObject() =default;
~UniqueObject() =default;
UniqueObject(const UniqueObject &obj) =delete;
UniqueObject &operator=(const UniqueObject &obj) =delete;
UniqueObject(UniqueObject &&obj) =default;
UniqueObject &operator=(UniqueObject &&obj) =default;
};
More modern C++ features?
 static_assert and type traits
 Mutable
 Constructor delegation
 http://www.nullptr.me/2012/01/17/c11-delegating-constructors/
 Uniform initialization
 http://programmers.stackexchange.com/questions/133688/is-c11-
uniform-initialization-a-replacement-for-the-old-style-syntax
 rvalue reference for *this
 http://stackoverflow.com/questions/12306226/what-does-an-ampersand-
after-this-assignment-operator-mean
 Many more…
Follow me on:
Twitter: @MihaiTodor
Linkedin: www.linkedin.com/mtodor
See my activity on StackOverflow:
http://stackoverflow.com/users/1174378/mihai-todor

More Related Content

What's hot

What's New in C++ 11?
What's New in C++ 11?What's New in C++ 11?
What's New in C++ 11?
Sasha Goldshtein
 
C++11: Rvalue References, Move Semantics, Perfect Forwarding
C++11: Rvalue References, Move Semantics, Perfect ForwardingC++11: Rvalue References, Move Semantics, Perfect Forwarding
C++11: Rvalue References, Move Semantics, Perfect Forwarding
Francesco Casalegno
 
C++11
C++11C++11
C++ Presentation
C++ PresentationC++ Presentation
C++ Presentation
Carson Wilber
 
C++ 11
C++ 11C++ 11
Smart Pointers in C++
Smart Pointers in C++Smart Pointers in C++
Smart Pointers in C++
Francesco Casalegno
 
C++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabsC++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabs
Stephane Gleizes
 
The Style of C++ 11
The Style of C++ 11The Style of C++ 11
The Style of C++ 11
Sasha Goldshtein
 
Regular types in C++
Regular types in C++Regular types in C++
Regular types in C++
Ilio Catallo
 
Summary of C++17 features
Summary of C++17 featuresSummary of C++17 features
Summary of C++17 features
Bartlomiej Filipek
 
Smart pointers
Smart pointersSmart pointers
Smart pointers
Vishal Mahajan
 
Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)
Sumant Tambe
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Chris Adamson
 
Design Patterns in Modern C++
Design Patterns in Modern C++Design Patterns in Modern C++
Design Patterns in Modern C++
Dmitri Nesteruk
 
C++ Training
C++ TrainingC++ Training
C++ Training
SubhendraBasu5
 
Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)
Sumant Tambe
 
Modern C++ Explained: Move Semantics (Feb 2018)
Modern C++ Explained: Move Semantics (Feb 2018)Modern C++ Explained: Move Semantics (Feb 2018)
Modern C++ Explained: Move Semantics (Feb 2018)
Olve Maudal
 
STL ALGORITHMS
STL ALGORITHMSSTL ALGORITHMS
STL ALGORITHMS
fawzmasood
 
(5) cpp dynamic memory_arrays_and_c-strings
(5) cpp dynamic memory_arrays_and_c-strings(5) cpp dynamic memory_arrays_and_c-strings
(5) cpp dynamic memory_arrays_and_c-strings
Nico Ludwig
 
C++ references
C++ referencesC++ references
C++ references
corehard_by
 

What's hot (20)

What's New in C++ 11?
What's New in C++ 11?What's New in C++ 11?
What's New in C++ 11?
 
C++11: Rvalue References, Move Semantics, Perfect Forwarding
C++11: Rvalue References, Move Semantics, Perfect ForwardingC++11: Rvalue References, Move Semantics, Perfect Forwarding
C++11: Rvalue References, Move Semantics, Perfect Forwarding
 
C++11
C++11C++11
C++11
 
C++ Presentation
C++ PresentationC++ Presentation
C++ Presentation
 
C++ 11
C++ 11C++ 11
C++ 11
 
Smart Pointers in C++
Smart Pointers in C++Smart Pointers in C++
Smart Pointers in C++
 
C++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabsC++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabs
 
The Style of C++ 11
The Style of C++ 11The Style of C++ 11
The Style of C++ 11
 
Regular types in C++
Regular types in C++Regular types in C++
Regular types in C++
 
Summary of C++17 features
Summary of C++17 featuresSummary of C++17 features
Summary of C++17 features
 
Smart pointers
Smart pointersSmart pointers
Smart pointers
 
Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
 
Design Patterns in Modern C++
Design Patterns in Modern C++Design Patterns in Modern C++
Design Patterns in Modern C++
 
C++ Training
C++ TrainingC++ Training
C++ Training
 
Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)
 
Modern C++ Explained: Move Semantics (Feb 2018)
Modern C++ Explained: Move Semantics (Feb 2018)Modern C++ Explained: Move Semantics (Feb 2018)
Modern C++ Explained: Move Semantics (Feb 2018)
 
STL ALGORITHMS
STL ALGORITHMSSTL ALGORITHMS
STL ALGORITHMS
 
(5) cpp dynamic memory_arrays_and_c-strings
(5) cpp dynamic memory_arrays_and_c-strings(5) cpp dynamic memory_arrays_and_c-strings
(5) cpp dynamic memory_arrays_and_c-strings
 
C++ references
C++ referencesC++ references
C++ references
 

Viewers also liked

Fion's Image Gallery
Fion's Image GalleryFion's Image Gallery
Fion's Image Gallery
tse_fionkl
 
Destination Dog Pitch
Destination Dog PitchDestination Dog Pitch
Destination Dog Pitch
ashley_willis
 
NPS Q1 report
NPS Q1 reportNPS Q1 report
NPS Q1 report
Adriana Bozbiciu
 
Specific questions Adriana Bozbiciu
Specific questions  Adriana BozbiciuSpecific questions  Adriana Bozbiciu
Specific questions Adriana Bozbiciu
Adriana Bozbiciu
 
Fion's major assignment image gallery
Fion's major assignment image galleryFion's major assignment image gallery
Fion's major assignment image gallery
tse_fionkl
 
Fion's Image Gallery
Fion's Image GalleryFion's Image Gallery
Fion's Image Gallery
tse_fionkl
 
Raport q4
Raport q4Raport q4
Raport q4
Adriana Bozbiciu
 
Fion's Image Gallery
Fion's Image GalleryFion's Image Gallery
Fion's Image Gallery
tse_fionkl
 
General questions Adriana Bozbiciu
General questions   Adriana BozbiciuGeneral questions   Adriana Bozbiciu
General questions Adriana Bozbiciu
Adriana Bozbiciu
 
Raport Q1 AIESEC Romania
Raport Q1 AIESEC RomaniaRaport Q1 AIESEC Romania
Raport Q1 AIESEC Romania
Adriana Bozbiciu
 
Minimal Introduction to C++ - Part I
Minimal Introduction to C++ - Part IMinimal Introduction to C++ - Part I
Minimal Introduction to C++ - Part I
Michel Alves
 
2 Intro c++
2 Intro c++2 Intro c++
2 Intro c++
Docent Education
 
Minimal Introduction to C++ - Part II
Minimal Introduction to C++ - Part IIMinimal Introduction to C++ - Part II
Minimal Introduction to C++ - Part II
Michel Alves
 
Minimal Introduction to C++ - Part III - Final
Minimal Introduction to C++ - Part III - FinalMinimal Introduction to C++ - Part III - Final
Minimal Introduction to C++ - Part III - Final
Michel Alves
 
Aiesec romania data report pre q1
Aiesec romania data report pre q1Aiesec romania data report pre q1
Aiesec romania data report pre q1
Adriana Bozbiciu
 
DNB-Final PMR Question papers 2010 to 2013
DNB-Final PMR Question papers 2010 to 2013DNB-Final PMR Question papers 2010 to 2013
DNB-Final PMR Question papers 2010 to 2013
Amit Ranjan
 
C++ Introduction
C++ IntroductionC++ Introduction
C++ Introduction
parmsidhu
 
Chapter 01 - introduction for C++
Chapter 01 - introduction for C++Chapter 01 - introduction for C++
Chapter 01 - introduction for C++
wahida_f6
 
An Introduction to C++ A complete beginners guide - Michael Oliver
An Introduction to C++ A complete beginners guide - Michael OliverAn Introduction to C++ A complete beginners guide - Michael Oliver
An Introduction to C++ A complete beginners guide - Michael Oliver
cttvl
 

Viewers also liked (20)

Fion's Image Gallery
Fion's Image GalleryFion's Image Gallery
Fion's Image Gallery
 
Destination Dog Pitch
Destination Dog PitchDestination Dog Pitch
Destination Dog Pitch
 
NPS Q1 report
NPS Q1 reportNPS Q1 report
NPS Q1 report
 
Specific questions Adriana Bozbiciu
Specific questions  Adriana BozbiciuSpecific questions  Adriana Bozbiciu
Specific questions Adriana Bozbiciu
 
Fion's major assignment image gallery
Fion's major assignment image galleryFion's major assignment image gallery
Fion's major assignment image gallery
 
Fion's Image Gallery
Fion's Image GalleryFion's Image Gallery
Fion's Image Gallery
 
Raport q4
Raport q4Raport q4
Raport q4
 
Up ftour11
Up ftour11Up ftour11
Up ftour11
 
Fion's Image Gallery
Fion's Image GalleryFion's Image Gallery
Fion's Image Gallery
 
General questions Adriana Bozbiciu
General questions   Adriana BozbiciuGeneral questions   Adriana Bozbiciu
General questions Adriana Bozbiciu
 
Raport Q1 AIESEC Romania
Raport Q1 AIESEC RomaniaRaport Q1 AIESEC Romania
Raport Q1 AIESEC Romania
 
Minimal Introduction to C++ - Part I
Minimal Introduction to C++ - Part IMinimal Introduction to C++ - Part I
Minimal Introduction to C++ - Part I
 
2 Intro c++
2 Intro c++2 Intro c++
2 Intro c++
 
Minimal Introduction to C++ - Part II
Minimal Introduction to C++ - Part IIMinimal Introduction to C++ - Part II
Minimal Introduction to C++ - Part II
 
Minimal Introduction to C++ - Part III - Final
Minimal Introduction to C++ - Part III - FinalMinimal Introduction to C++ - Part III - Final
Minimal Introduction to C++ - Part III - Final
 
Aiesec romania data report pre q1
Aiesec romania data report pre q1Aiesec romania data report pre q1
Aiesec romania data report pre q1
 
DNB-Final PMR Question papers 2010 to 2013
DNB-Final PMR Question papers 2010 to 2013DNB-Final PMR Question papers 2010 to 2013
DNB-Final PMR Question papers 2010 to 2013
 
C++ Introduction
C++ IntroductionC++ Introduction
C++ Introduction
 
Chapter 01 - introduction for C++
Chapter 01 - introduction for C++Chapter 01 - introduction for C++
Chapter 01 - introduction for C++
 
An Introduction to C++ A complete beginners guide - Michael Oliver
An Introduction to C++ A complete beginners guide - Michael OliverAn Introduction to C++ A complete beginners guide - Michael Oliver
An Introduction to C++ A complete beginners guide - Michael Oliver
 

Similar to Gentle introduction to modern C++

LLVM
LLVMLLVM
67404923-C-Programming-Tutorials-Doc.pdf
67404923-C-Programming-Tutorials-Doc.pdf67404923-C-Programming-Tutorials-Doc.pdf
67404923-C-Programming-Tutorials-Doc.pdf
Rajb54
 
C_plus_plus
C_plus_plusC_plus_plus
C_plus_plus
Ralph Weber
 
C tutorials
C tutorialsC tutorials
C tutorials
Amit Kapoor
 
C++ language
C++ languageC++ language
C++ language
Hamza Asif
 
C# features
C# featuresC# features
C# features
sagaroceanic11
 
Learn c language Important topics ( Easy & Logical, & smart way of learning)
Learn c language Important topics ( Easy & Logical, & smart way of learning)Learn c language Important topics ( Easy & Logical, & smart way of learning)
Learn c language Important topics ( Easy & Logical, & smart way of learning)
Rohit Singh
 
C++ programming language basic to advance level
C++ programming language basic to advance levelC++ programming language basic to advance level
C++ programming language basic to advance level
sajjad ali khan
 
Gude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerGude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic Server
Apache Traffic Server
 
Basic c
Basic cBasic c
Basic c
Veera Karthi
 
2.Overview of C language.pptx
2.Overview of C language.pptx2.Overview of C language.pptx
2.Overview of C language.pptx
Vishwas459764
 
COM Introduction
COM IntroductionCOM Introduction
COM Introduction
Roy Antony Arnold G
 
C programming
C programmingC programming
C programming
Rounak Samdadia
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and Beyond
ComicSansMS
 
C Language Presentation.pptx
C Language Presentation.pptxC Language Presentation.pptx
C Language Presentation.pptx
PradeepKumar206701
 
CSharp Presentation
CSharp PresentationCSharp Presentation
CSharp Presentation
Vishwa Mohan
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
Sangharsh agarwal
 
C programming
C programmingC programming
C by balaguruswami - e.balagurusamy
C   by balaguruswami - e.balagurusamyC   by balaguruswami - e.balagurusamy
C by balaguruswami - e.balagurusamy
Srichandan Sobhanayak
 
C material
C materialC material
C material
tarique472
 

Similar to Gentle introduction to modern C++ (20)

LLVM
LLVMLLVM
LLVM
 
67404923-C-Programming-Tutorials-Doc.pdf
67404923-C-Programming-Tutorials-Doc.pdf67404923-C-Programming-Tutorials-Doc.pdf
67404923-C-Programming-Tutorials-Doc.pdf
 
C_plus_plus
C_plus_plusC_plus_plus
C_plus_plus
 
C tutorials
C tutorialsC tutorials
C tutorials
 
C++ language
C++ languageC++ language
C++ language
 
C# features
C# featuresC# features
C# features
 
Learn c language Important topics ( Easy & Logical, & smart way of learning)
Learn c language Important topics ( Easy & Logical, & smart way of learning)Learn c language Important topics ( Easy & Logical, & smart way of learning)
Learn c language Important topics ( Easy & Logical, & smart way of learning)
 
C++ programming language basic to advance level
C++ programming language basic to advance levelC++ programming language basic to advance level
C++ programming language basic to advance level
 
Gude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerGude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic Server
 
Basic c
Basic cBasic c
Basic c
 
2.Overview of C language.pptx
2.Overview of C language.pptx2.Overview of C language.pptx
2.Overview of C language.pptx
 
COM Introduction
COM IntroductionCOM Introduction
COM Introduction
 
C programming
C programmingC programming
C programming
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and Beyond
 
C Language Presentation.pptx
C Language Presentation.pptxC Language Presentation.pptx
C Language Presentation.pptx
 
CSharp Presentation
CSharp PresentationCSharp Presentation
CSharp Presentation
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
C programming
C programmingC programming
C programming
 
C by balaguruswami - e.balagurusamy
C   by balaguruswami - e.balagurusamyC   by balaguruswami - e.balagurusamy
C by balaguruswami - e.balagurusamy
 
C material
C materialC material
C material
 

Recently uploaded

Optimizing Your E-commerce with WooCommerce.pptx
Optimizing Your E-commerce with WooCommerce.pptxOptimizing Your E-commerce with WooCommerce.pptx
Optimizing Your E-commerce with WooCommerce.pptx
WebConnect Pvt Ltd
 
Strengthening Web Development with CommandBox 6: Seamless Transition and Scal...
Strengthening Web Development with CommandBox 6: Seamless Transition and Scal...Strengthening Web Development with CommandBox 6: Seamless Transition and Scal...
Strengthening Web Development with CommandBox 6: Seamless Transition and Scal...
Ortus Solutions, Corp
 
Call Girls Bangalore🔥7023059433🔥Best Profile Escorts in Bangalore Available 24/7
Call Girls Bangalore🔥7023059433🔥Best Profile Escorts in Bangalore Available 24/7Call Girls Bangalore🔥7023059433🔥Best Profile Escorts in Bangalore Available 24/7
Call Girls Bangalore🔥7023059433🔥Best Profile Escorts in Bangalore Available 24/7
manji sharman06
 
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data PlatformAlluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio, Inc.
 
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
The Third Creative Media
 
The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024
Yara Milbes
 
Refactoring legacy systems using events commands and bubble contexts
Refactoring legacy systems using events commands and bubble contextsRefactoring legacy systems using events commands and bubble contexts
Refactoring legacy systems using events commands and bubble contexts
Michał Kurzeja
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
Tier1 app
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
kalichargn70th171
 
The Role of DevOps in Digital Transformation.pdf
The Role of DevOps in Digital Transformation.pdfThe Role of DevOps in Digital Transformation.pdf
The Role of DevOps in Digital Transformation.pdf
mohitd6
 
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
kgyxske
 
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptxOperational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
sandeepmenon62
 
Computer Science & Engineering VI Sem- New Syllabus.pdf
Computer Science & Engineering VI Sem- New Syllabus.pdfComputer Science & Engineering VI Sem- New Syllabus.pdf
Computer Science & Engineering VI Sem- New Syllabus.pdf
chandangoswami40933
 
Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)
alowpalsadig
 
Secure-by-Design Using Hardware and Software Protection for FDA Compliance
Secure-by-Design Using Hardware and Software Protection for FDA ComplianceSecure-by-Design Using Hardware and Software Protection for FDA Compliance
Secure-by-Design Using Hardware and Software Protection for FDA Compliance
ICS
 
ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.
Maitrey Patel
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid
 
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
campbellclarkson
 
Software Test Automation - A Comprehensive Guide on Automated Testing.pdf
Software Test Automation - A Comprehensive Guide on Automated Testing.pdfSoftware Test Automation - A Comprehensive Guide on Automated Testing.pdf
Software Test Automation - A Comprehensive Guide on Automated Testing.pdf
kalichargn70th171
 
Building API data products on top of your real-time data infrastructure
Building API data products on top of your real-time data infrastructureBuilding API data products on top of your real-time data infrastructure
Building API data products on top of your real-time data infrastructure
confluent
 

Recently uploaded (20)

Optimizing Your E-commerce with WooCommerce.pptx
Optimizing Your E-commerce with WooCommerce.pptxOptimizing Your E-commerce with WooCommerce.pptx
Optimizing Your E-commerce with WooCommerce.pptx
 
Strengthening Web Development with CommandBox 6: Seamless Transition and Scal...
Strengthening Web Development with CommandBox 6: Seamless Transition and Scal...Strengthening Web Development with CommandBox 6: Seamless Transition and Scal...
Strengthening Web Development with CommandBox 6: Seamless Transition and Scal...
 
Call Girls Bangalore🔥7023059433🔥Best Profile Escorts in Bangalore Available 24/7
Call Girls Bangalore🔥7023059433🔥Best Profile Escorts in Bangalore Available 24/7Call Girls Bangalore🔥7023059433🔥Best Profile Escorts in Bangalore Available 24/7
Call Girls Bangalore🔥7023059433🔥Best Profile Escorts in Bangalore Available 24/7
 
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data PlatformAlluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
 
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
 
The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024
 
Refactoring legacy systems using events commands and bubble contexts
Refactoring legacy systems using events commands and bubble contextsRefactoring legacy systems using events commands and bubble contexts
Refactoring legacy systems using events commands and bubble contexts
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
 
The Role of DevOps in Digital Transformation.pdf
The Role of DevOps in Digital Transformation.pdfThe Role of DevOps in Digital Transformation.pdf
The Role of DevOps in Digital Transformation.pdf
 
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
 
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptxOperational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
 
Computer Science & Engineering VI Sem- New Syllabus.pdf
Computer Science & Engineering VI Sem- New Syllabus.pdfComputer Science & Engineering VI Sem- New Syllabus.pdf
Computer Science & Engineering VI Sem- New Syllabus.pdf
 
Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)
 
Secure-by-Design Using Hardware and Software Protection for FDA Compliance
Secure-by-Design Using Hardware and Software Protection for FDA ComplianceSecure-by-Design Using Hardware and Software Protection for FDA Compliance
Secure-by-Design Using Hardware and Software Protection for FDA Compliance
 
ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
 
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
 
Software Test Automation - A Comprehensive Guide on Automated Testing.pdf
Software Test Automation - A Comprehensive Guide on Automated Testing.pdfSoftware Test Automation - A Comprehensive Guide on Automated Testing.pdf
Software Test Automation - A Comprehensive Guide on Automated Testing.pdf
 
Building API data products on top of your real-time data infrastructure
Building API data products on top of your real-time data infrastructureBuilding API data products on top of your real-time data infrastructure
Building API data products on top of your real-time data infrastructure
 

Gentle introduction to modern C++

  • 1. Gentle* Introduction to Modern C++ Mihai Todor * Well, maybe not so gentle  Disclaimer: This presentation is focused on C++11 features and assumes a basic understanding of C++
  • 2. Intro I  C++ is boring / hard to get right  The C++ compilers are buggy  We don’t want to mess with it
  • 3. Intro II And your code looks like this*: *That’s actually C# code, but you get the point 
  • 5. Intro IV In spite of the fact that it lacks some of the C# flexibility and compactness, C++ is a beautiful language, having a rich syntax, which enables a high degree of expressivity and abstraction, with a fine grained control over resource consumption.
  • 6. Intro V  If done right, in C++ you only pay for what you use  If done wrong, in C++ you blow your entire leg off, not just a toe
  • 7. Intro VI  The compiler is never* wrong  C++11 features alleviate much of the pain we had to endure when architecting code  The STL is becoming richer and more flexible  Compilers are adopting new features much faster *well, maybe sometimes, but it usually requires more than 10 minutes of coding to stumble upon a legit compiler bug
  • 8. Some modern C++ features  Move semantics  Auto  nullptr  Range-based for loops  override and final  Strongly-typed enums  Lambdas  Explicitly defaulted and deleted functions  Smart pointers
  • 9. Move semantics  Copies are expensive!  Want speed, pass by value (not always*)  Moving variables can be as cheap as a pointer swap  Classes can now have move constructors and move assignment operators * http://juanchopanzacpp.wordpress.com/2014/05/11/want-speed-dont-always-pass-by-value/
  • 10. Move semantics II  In C++11, an expression can be: The && operator has been introduced in order to declare an rvalue reference Diagram shamelessly ripped from here: http://stackoverflow.com/a/3601748/1174378
  • 11. Move semantics III  xvalue (an “eXpiring” value) – also refers to an object, usually near the end of its lifetime  A type Type followed by && represents an rvalue reference  xvalues are explicit moves, created by std::move  prvalue (“pure” rvalue) - an rvalue that is not an xvalue (implicit moves)
  • 12. Move semantics IV  A reference type that is declared using & is called an lvalue reference  A reference type that is declared using && is called an rvalue reference.
  • 13. Move semantics V  Powerful tools in the <utility> header:  std::move  std::forward  std::make_move_iterator A thorough explanation for std::move and std::forward: http://blogs.msdn.com/b/vcblog/archive/2009/02/03/rvalue-references-c-0x-features-in-vc10-part-2.aspx
  • 14. auto  Repurposed keyword (initially, it designated a storage duration specifier)  Similar to C#’s var keyword  Reduces code verbosity by deducing a variable’s type from the initializer  Also allows return type deduction (C++14)  Potential for abuse!
  • 15. nullptr  Eliminates the ambiguous conversion between NULL (#defined as 0) and integral types  Denotes a value of type std::nullptr_t  Converts implicitly to bool (as false) and null pointer values of any type  You don’t have to test a variable for null with both NULL and nullptr! int *pointer = LegacyGetInt(); if (pointer != nullptr && pointer != NULL)//both tests are equivalent
  • 16. Range-based for loops  They resemble the C# foreach statement  Syntax: for (auto value: collection) {/* do stuff */}  the type specifier of value determines how the collection items are iterated: by value, by reference, by const reference, etc  Can be used with any type for which non-member overloads of the begin() and end() functions are implemented  see NonMemberBeginAndEnd.cpp
  • 17. override and final  If override is added to the declaration of a virtual method, which does not override a virtual method from the base class, the compiler emits an error  If final is added to the declaration of a virtual method, then derived classes are not allowed to override this method  in C++, the virtual specifier is optional for derived class override methods  If final is added to the declaration of a class, then no other classes can derive from that class. This resembles C#’s sealed keyword
  • 18. Strongly-typed enums  Eliminate issues caused by regular enums: namespace pollution and implicit conversions  For now, there is no simple way to use these in the same way as a C# flags enum (tagged enumeration)  The enum class underlying type can be specified by the user: enum class Colors : std::int8_t { RED = 1, GREEN = 2, BLUE = 3 };  Extracting underlying values of an enum class requires an explicit cast: auto blue = static_cast<std::underlying_type<Colors>::type>(Colors::Blue);
  • 19. Smart pointers  They provide reference counting in order to enable the automatic release of memory  Concerns about performance degradation / extra memory consumption are, indeed, legitimate, but in most cases we are not creating millions of objects on the heap to have really tight constraints  std::unique_ptr – Guarantees unique ownership of a memory resource. It cannot be copied (only moved to another std::unique_ptr).  Created with std::make_unique (C++14)  std::auto_ptr is obsolete! Please replace it on sight with std::unique_ptr.
  • 20. Smart pointers II  std::shared_ptr – Allows shared ownership of a memory resource  Created with std::make_shared (C++11)  std::weak_ptr – Holds a reference to an object managed by an std::shared_ptr.  does not contribute to the reference count  Ensures that cycles are broken  std::static_pointer_cast, std::dynamic_pointer_cast and std::const_pointer_cast are your friends!
  • 21. Lambdas  C++11 introduces support for anonymous functions, namely lambdas  Fine-grained control over variable capture  By default, variables captured by value are const, unless the mutable specification is present  We can have recursive lambdas
  • 22. Lambdas II  Syntax (shamelessly ripped from MSDN*) 1. lambda-introducer (Also known as the capture clause) 2. lambda declarator (Also known as the parameter list). Optional! 3. mutable (Also known as the mutable specification) . Optional! 4. exception-specification (Also known as the exception specification) . Optional! 5. trailing-return-type (Also known as the return type) . Optional! 6. compound-statement (Also known as the lambda body) * http://msdn.microsoft.com/en-us/library/dd293603.aspx
  • 23. Explicitly defaulted and deleted functions  The rules which specify when the implicitly- declared default constructor and destructor, copy and move constructors and copy and move assignment operators get generated are somewhat complex, so C++11 allows you to force the compiler to generate them or not, via the =default and =delete specifiers.  Please take the Rules of three/five/zero into account when using these specifiers!
  • 24. Explicitly defaulted and deleted functions II  Let’s design a trivial object, which can be constructed and moved, but not copied class UniqueObject { public: UniqueObject() =default; ~UniqueObject() =default; UniqueObject(const UniqueObject &obj) =delete; UniqueObject &operator=(const UniqueObject &obj) =delete; UniqueObject(UniqueObject &&obj) =default; UniqueObject &operator=(UniqueObject &&obj) =default; };
  • 25. More modern C++ features?  static_assert and type traits  Mutable  Constructor delegation  http://www.nullptr.me/2012/01/17/c11-delegating-constructors/  Uniform initialization  http://programmers.stackexchange.com/questions/133688/is-c11- uniform-initialization-a-replacement-for-the-old-style-syntax  rvalue reference for *this  http://stackoverflow.com/questions/12306226/what-does-an-ampersand- after-this-assignment-operator-mean  Many more…
  • 26. Follow me on: Twitter: @MihaiTodor Linkedin: www.linkedin.com/mtodor See my activity on StackOverflow: http://stackoverflow.com/users/1174378/mihai-todor