SlideShare a Scribd company logo
C++11
Feel the new language
Where is C++?
What’s special about C++
    Lightweight abstraction programming language
                                          B.Stroustrup


•   Build abstractions at little or no cost
•   Without sacrificing transparency
•   Without sacrificing performance
•   Pay as you go
•   Dive under the hood whenever you like
What makes C++11 different
Direct language support for powerful patterns
  E.g.   Lambdas, move semantics
Incorporating best practices and libs into STL
  – Smart pointers, regular expressions
  E.g.



Catch-up with the modern hardware
  – Multi-threaded memory model
  E.g.



Shifting programming style to higher level
  – Naked pointers are persona non grata
  E.g.
What is a lightweight abstraction?
goto:
  – Low-level (machine thinking)
  – Welcome to spaghetti code

if-then-else, while-loop, loop-until:
  –   Abstracise goto
  –   High-level, meaningful (human thinking)
  –   Composable, self-contained building blocks
  –   Transparent
  –   No performance cost
  –   Can still use goto if necessary
Smart pointers and Resource
         Handling
Lightweight abstraction: memory
Raw pointers (T*):
  – Low-level (machine thinking)
  – Welcome to crashes and memory leaks


Smart pointers (unique_ptr<T>, shared_ptr<T>):
  –   Abstracise raw pointers
  –   High-level, meaningful (human thinking)
  –   Transparent
  –   Little or no performance cost
  –   Can still use raw pointers if necessary
Raw pointers (or HANDLEs)

widget *getWidget();
void foo()
{
    widget *pw = getWidget();
    // Don’t know if we’re sharing the widget with someone else
    // Don’t know if we must delete pw when done
    // Have to manually take care about exception-safety
    …
}
unique_ptr<T>
•   Ownership semantics
•   Think auto_ptr<T> done right
•   Calls delete or delete[] in destructor
•   Movable, but not copyable (see Move Semantics later)
•   No runtime overhead

#include <memory>
std::unique_ptr<widget> getWidget();
void foo()
{
    std::unique_ptr<widget> pw{ getWidget() };
    // The widget is exclusively ours
    // We can’t accidentally share it
    // It will be deleted automatically and exception-safe
}
shared_ptr<T>
•   Ref-counting semantics                    shared_ptr<T>        T


•   Last one calls delete in destructor
•   Transparent and deterministic             shared_ptr<T>

•   Ref-counting and synchronization overhead
•   Use make_shared to reduce overhead        shared_ptr<T>
                                                              counter
                                                              control block
•   Use weak_ptr to break cycles

#include <memory>
std::shared_ptr<widget> getWidget();
void foo()
{
    std::shared_ptr<widget> pw{ getWidget() };
    // The widget may be shared
    // We don’t own it so we don’t care about deleting it
}
Resource Acquisition is Initialization
void f()
{
    database *pdb = open_database("mydb");
    … // What if we return or throw here?
    close_database(pdb);
}




class DBConnection
{
private:
    database *_pdb;
public:
    explicit DBConnection(const char *name) : pdb(open_database(dbname)) {}
    ~DBConnection() { close_database(pdb); }
}
void f()
{
    DBConnection dbc("mydb");
    … // The db connection is guaranteed to close properly
}
Resource Acquisition is Initialization
• GC in other languages only handles one
  resource - memory
• RAII in C++ has been around for over a decade
• C++11 encourages its use as default
• Smart pointers help building RAII around
  legacy interfaces
• Move semantics makes passing resources
  around cheap
Tradeoff That Isn’t
C++11: Feel the New Language
C++11: Feel the New Language
C++11: Feel the New Language
What’s wrong with low-level?
•    Unsafe? – Yes
•    Tedious? – Yes
•    Gets in the way of DRY? – Yes
•    Best performance? – No. May even make it worse

    Low-level programming is a powerful and
    complex tool, but it doesn’t guarantee you any
    advantage unless used properly.
Move Semantics
Value semantics as copy semantics
• Value semantics traditionally means copy-semantics
• Which means object gets copied when travels from one
  place to another
• Which makes returning an object from a function expensive
 Matrix operator+( const Matrix& a, const Matrix& b )
 {
     Matrix r;
     // Loop with r[i,j] = a[i,j]+b[i,j]
     return r; // Copying happens here – expensive
 }

• Which requires ugly workarounds
 void operator+( const Matrix& a, const Matrix& b, Matrix& r )
 {
     // Loop with r[i,j] = a[i,j]+b[i,j]
 }
C++11: Feel the New Language
C++11: Feel the New Language
C++11: Feel the New Language
Move constructor (and =)
template <typename T> class Matrix
{
private:
    unsigned int m; // Number of rows
    unsigned int n; // Number of columns
    T *pelems;      // Pointer to an array of m*n elements
public:
    …
     // Copy constructor
     Matrix( const Matrix& other ) : m(other.m), n(other.n)
     {
         pelems = new T[m*n];
         memcpy( pelems, other.pelems, m*n*sizeof(T) );
     }
     // Move constructor
     Matrix( Matrix&& other )
     {
         pelems = other.pelems;
         other.pelems = nullptr;
     }
     ~Matrix(){ delete[] pelems; }
};
Move semantics
         Matrix m = a * transpose(b) + c * inv(d);



•   Readable
•   Efficient
•   Safe
•   Meaningful
•   Backward-compatible
•   Fully supported by STL
Rvalue references
 Matrix( const Matrix& other ); // const lvalue ref
 Matrix( Matrix&& other );      // non-const rvalue ref



• The right function is selected through overload
  resolution
• Rvalue reference is preferred when called with rvalue
• Non-constness of the rvalue reference allows to modify
  the rvalue
• Bonus: perfect forwarding
Copy or Move?
• Implicit
  Matrix f( const Matrix& a )
  {
      Matrix r(a); // copy: a can be used below, don’t mess with it
      …
      return r;    // move: r is on its last leg
  }


• Explicit
  Matrix f()
  {
      Matrix e{ {1,0}, {0,1} };
      Matrix r( std::move(e) ); // forced move: e is zombie now and
      …                         // using it would be a bad idea
  }
Lambdas



  λ
Life before lambdas
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
struct DivisibilityPredicateFunctor
{
    int m_d;
    DivisibilityPredicate( int d ) : m_d(d) {}
    bool operator()( int n ) const { return n % m_d == 0; }
};
void OutputFunction( int n )
{
    cout << n << endl;
};
vector<int> remove_multiples( vector<int> v, int d )
{
    vector<int> r;
    remove_copy_if( begin(v), end(v), back_inserter(r), DivisibilityPredicateFunctor(d) );
    return r;
}
void main()
{
    vector<int> v;
    int array[] = {0,1,2,3,4,5,6,7,8,9};
    for( int i = 0; i < sizeof array/sizeof *array; ++i )
        v.push_back( array[i] );
    vector<int> m = remove_multiples( v, 3 );
    for_each( begin(m), end(m), OutputFunction );
}
Life in C++11
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
vector<int> remove_multiples( vector<int> v, int d )
{
    vector<int> r;
    remove_copy_if( begin(v), end(v), back_inserter(r), [=](int n){ return n % d == 0; } );
    return r;
}
void main()
{
    vector<int> m = remove_multiples( {0,1,2,3,4,5,6,7,8,9}, 3 );
    for_each( begin(m), end(m), [](int n){ cout << n << endl; } );
}
Lambdas
• Without jumping through hoops now:
   – STL algorithms
   – Callbacks
   – Threading
• Foundation for higher-level stuff:
   – Async programming
   – Functional programming

C++ flavor: you have fine-grained control over
environment capture.
Lambda anatomy
                            return type
  lambda introducer                       captured variable



     [=] (int n) -> int { return n % d == 0; }

               parameter list
capture list                                     body
Lambda physiology
  • For each lambda compiler generates a class
                         struct CompilerGeneratedFunctor
                         {
[d](int n)->bool             int m_d;
{                            CompilerGeneratedFunctor(int d) : m_d(d) {}
                             bool operator()(int n) const
    return n % d == 0;       {
}                                return n % m_d == 0;
                             }
                         };



 • Specifying lambda instantiates an object
 • Invoking lambda calls the object’s operator()
 • Everything is easily inlinable
Lambda physiology

  • Lambda with empty capture list is just a function

[](int n)->bool          bool CompilerGeneratedFunction(int n)
{                        {
    return n % 2 == 0;       return n % 2 == 0;
                         }
}




 • Inlining is even easier
Variable capture


By value      By reference       Mix
[=]             [&]            [=, &x, &y]
[x, y, z]       [&x, &y, &z]   [&, x, y]
Recommended watching
http://channel9.msdn.com/Events/GoingNative/GoingNative-2012

More Related Content

PDF
Modern C++
Michael Clark
 
PPT
Gentle introduction to modern C++
Mihai Todor
 
PDF
C++11 & C++14
CyberPlusIndia
 
PPTX
C++ 11 Features
Jan Rüegg
 
PPTX
C++11
Sasha Goldshtein
 
PPTX
C++11
Andrey Dankevich
 
PDF
C++11
ppd1961
 
PDF
Modern c++ (C++ 11/14)
Geeks Anonymes
 
Modern C++
Michael Clark
 
Gentle introduction to modern C++
Mihai Todor
 
C++11 & C++14
CyberPlusIndia
 
C++ 11 Features
Jan Rüegg
 
C++11
ppd1961
 
Modern c++ (C++ 11/14)
Geeks Anonymes
 

What's hot (20)

PPTX
C++11
Quang Trần Duy
 
PDF
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
Francesco Casalegno
 
PPT
What's New in C++ 11?
Sasha Goldshtein
 
PDF
C++11 concurrency
xu liwei
 
PDF
C++11: Rvalue References, Move Semantics, Perfect Forwarding
Francesco Casalegno
 
PPTX
C++ 11
Denys Haryachyy
 
PPTX
C++ Presentation
Carson Wilber
 
PDF
Smart Pointers in C++
Francesco Casalegno
 
PPTX
The Style of C++ 11
Sasha Goldshtein
 
PDF
Le langage rust
Geeks Anonymes
 
PPTX
Summary of C++17 features
Bartlomiej Filipek
 
PDF
C++17 introduction - Meetup @EtixLabs
Stephane Gleizes
 
PDF
Regular types in C++
Ilio Catallo
 
PPTX
Smart pointers
Vishal Mahajan
 
PDF
Fun with Lambdas: C++14 Style (part 1)
Sumant Tambe
 
PPTX
Fun with Lambdas: C++14 Style (part 2)
Sumant Tambe
 
PPT
STL ALGORITHMS
fawzmasood
 
PDF
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Chris Adamson
 
PPTX
What's New in C++ 11/14?
Dina Goldshtein
 
PDF
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
kinan keshkeh
 
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
Francesco Casalegno
 
What's New in C++ 11?
Sasha Goldshtein
 
C++11 concurrency
xu liwei
 
C++11: Rvalue References, Move Semantics, Perfect Forwarding
Francesco Casalegno
 
C++ Presentation
Carson Wilber
 
Smart Pointers in C++
Francesco Casalegno
 
The Style of C++ 11
Sasha Goldshtein
 
Le langage rust
Geeks Anonymes
 
Summary of C++17 features
Bartlomiej Filipek
 
C++17 introduction - Meetup @EtixLabs
Stephane Gleizes
 
Regular types in C++
Ilio Catallo
 
Smart pointers
Vishal Mahajan
 
Fun with Lambdas: C++14 Style (part 1)
Sumant Tambe
 
Fun with Lambdas: C++14 Style (part 2)
Sumant Tambe
 
STL ALGORITHMS
fawzmasood
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Chris Adamson
 
What's New in C++ 11/14?
Dina Goldshtein
 
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
kinan keshkeh
 
Ad

Viewers also liked (17)

PDF
Big data: The next frontier for innovation, competition, and productivity
MARAM SRAVAN KUMAR
 
PPTX
Medieval presentation
mrsbrownsenglish
 
PPTX
The value of site testing
AlexSpez
 
DOC
Satu hari di majlis hi
Azie Maskan
 
DOC
Anugerah allah yang tiada nilai bandingnya
Azie Maskan
 
PDF
Taylor Root Salary Survey 2012 for West End, Niche and Boutique Law Firms
NickSmetana
 
PDF
a Case study on A V Birla Group - Legacy of Free Enterprise and Diversification
MARAM SRAVAN KUMAR
 
PPTX
Sawdust project
mrsbrownsenglish
 
PPT
Cjd may 19-25, 2012 post service calls
janinabaluyot
 
PPT
ВШ 2014 Лекция №2 - Безопасность и ориентирование
Alexander Korvyakov
 
PPTX
Entreprenuer ship businessplan
MARAM SRAVAN KUMAR
 
PPT
Subhanallah, hamil itu menakjubkan!
Azie Maskan
 
PPTX
ВШ 2014 - Лекция № 4 - "Валы, бочки, водопадные сливы" - Качанов
Alexander Korvyakov
 
PPTX
ВШ 2014. Лекция №5 - Виды водных препятствий
Alexander Korvyakov
 
PPTX
Medieval times
mrsbrownsenglish
 
PPTX
VJ Kurian & the CIAL Saga
MARAM SRAVAN KUMAR
 
PPT
ВШ 2014 - Лекция № 3 - типы судов. снаряжение для водного туризма
Alexander Korvyakov
 
Big data: The next frontier for innovation, competition, and productivity
MARAM SRAVAN KUMAR
 
Medieval presentation
mrsbrownsenglish
 
The value of site testing
AlexSpez
 
Satu hari di majlis hi
Azie Maskan
 
Anugerah allah yang tiada nilai bandingnya
Azie Maskan
 
Taylor Root Salary Survey 2012 for West End, Niche and Boutique Law Firms
NickSmetana
 
a Case study on A V Birla Group - Legacy of Free Enterprise and Diversification
MARAM SRAVAN KUMAR
 
Sawdust project
mrsbrownsenglish
 
Cjd may 19-25, 2012 post service calls
janinabaluyot
 
ВШ 2014 Лекция №2 - Безопасность и ориентирование
Alexander Korvyakov
 
Entreprenuer ship businessplan
MARAM SRAVAN KUMAR
 
Subhanallah, hamil itu menakjubkan!
Azie Maskan
 
ВШ 2014 - Лекция № 4 - "Валы, бочки, водопадные сливы" - Качанов
Alexander Korvyakov
 
ВШ 2014. Лекция №5 - Виды водных препятствий
Alexander Korvyakov
 
Medieval times
mrsbrownsenglish
 
VJ Kurian & the CIAL Saga
MARAM SRAVAN KUMAR
 
ВШ 2014 - Лекция № 3 - типы судов. снаряжение для водного туризма
Alexander Korvyakov
 
Ad

Similar to C++11: Feel the New Language (20)

PDF
Bjarne essencegn13
Hunde Gurmessa
 
PPTX
Whats New in Visual Studio 2012 for C++ Developers
Rainer Stropek
 
PPTX
Return of c++
Yongwei Wu
 
PDF
An Overview Of Standard C++Tr1
Ganesh Samarthyam
 
PPTX
C++11 - A Change in Style - v2.0
Yaser Zhian
 
PPTX
Smart-Pointers-and-Lambda-Functions-in-C.pptx
Samay Patil
 
PDF
Industry - Program analysis and verification - Type-preserving Heap Profiler ...
ICSM 2011
 
PDF
The Present and The Future of Functional Programming in C++
Alexander Granin
 
PPTX
C++11 - STL Additions
GlobalLogic Ukraine
 
PDF
Introduction to Compiler Development
Logan Chien
 
PDF
C++11 talk
vpoliboyina
 
PDF
The present and the future of functional programming in c++
Alexander Granin
 
PDF
Effective stl notes
Uttam Gandhi
 
PPTX
Useful C++ Features You Should be Using
Embarcadero Technologies
 
PPT
Stroustrup c++0x overview
Vaibhav Bajaj
 
PDF
C++ Training
SubhendraBasu5
 
PDF
Rainer Grimm, “Functional Programming in C++11”
Platonov Sergey
 
PDF
Milot Shala - C++ (OSCAL2014)
Open Labs Albania
 
PDF
Object Oriented Programming (OOP) using C++ - Lecture 4
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PPTX
Modern C++ Lunch and Learn
Paul Irwin
 
Bjarne essencegn13
Hunde Gurmessa
 
Whats New in Visual Studio 2012 for C++ Developers
Rainer Stropek
 
Return of c++
Yongwei Wu
 
An Overview Of Standard C++Tr1
Ganesh Samarthyam
 
C++11 - A Change in Style - v2.0
Yaser Zhian
 
Smart-Pointers-and-Lambda-Functions-in-C.pptx
Samay Patil
 
Industry - Program analysis and verification - Type-preserving Heap Profiler ...
ICSM 2011
 
The Present and The Future of Functional Programming in C++
Alexander Granin
 
C++11 - STL Additions
GlobalLogic Ukraine
 
Introduction to Compiler Development
Logan Chien
 
C++11 talk
vpoliboyina
 
The present and the future of functional programming in c++
Alexander Granin
 
Effective stl notes
Uttam Gandhi
 
Useful C++ Features You Should be Using
Embarcadero Technologies
 
Stroustrup c++0x overview
Vaibhav Bajaj
 
C++ Training
SubhendraBasu5
 
Rainer Grimm, “Functional Programming in C++11”
Platonov Sergey
 
Milot Shala - C++ (OSCAL2014)
Open Labs Albania
 
Object Oriented Programming (OOP) using C++ - Lecture 4
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Modern C++ Lunch and Learn
Paul Irwin
 

Recently uploaded (20)

PPTX
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
PPTX
Agile Chennai 18-19 July 2025 | Emerging patterns in Agentic AI by Bharani Su...
AgileNetwork
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PDF
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PPTX
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
PPTX
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
PDF
AI-Cloud-Business-Management-Platforms-The-Key-to-Efficiency-Growth.pdf
Artjoker Software Development Company
 
PPTX
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
PDF
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
PDF
Get More from Fiori Automation - What’s New, What Works, and What’s Next.pdf
Precisely
 
PDF
Doc9.....................................
SofiaCollazos
 
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
Agile Chennai 18-19 July 2025 | Emerging patterns in Agentic AI by Bharani Su...
AgileNetwork
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
AI-Cloud-Business-Management-Platforms-The-Key-to-Efficiency-Growth.pdf
Artjoker Software Development Company
 
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
Get More from Fiori Automation - What’s New, What Works, and What’s Next.pdf
Precisely
 
Doc9.....................................
SofiaCollazos
 

C++11: Feel the New Language

  • 3. What’s special about C++ Lightweight abstraction programming language B.Stroustrup • Build abstractions at little or no cost • Without sacrificing transparency • Without sacrificing performance • Pay as you go • Dive under the hood whenever you like
  • 4. What makes C++11 different Direct language support for powerful patterns E.g. Lambdas, move semantics Incorporating best practices and libs into STL – Smart pointers, regular expressions E.g. Catch-up with the modern hardware – Multi-threaded memory model E.g. Shifting programming style to higher level – Naked pointers are persona non grata E.g.
  • 5. What is a lightweight abstraction? goto: – Low-level (machine thinking) – Welcome to spaghetti code if-then-else, while-loop, loop-until: – Abstracise goto – High-level, meaningful (human thinking) – Composable, self-contained building blocks – Transparent – No performance cost – Can still use goto if necessary
  • 6. Smart pointers and Resource Handling
  • 7. Lightweight abstraction: memory Raw pointers (T*): – Low-level (machine thinking) – Welcome to crashes and memory leaks Smart pointers (unique_ptr<T>, shared_ptr<T>): – Abstracise raw pointers – High-level, meaningful (human thinking) – Transparent – Little or no performance cost – Can still use raw pointers if necessary
  • 8. Raw pointers (or HANDLEs) widget *getWidget(); void foo() { widget *pw = getWidget(); // Don’t know if we’re sharing the widget with someone else // Don’t know if we must delete pw when done // Have to manually take care about exception-safety … }
  • 9. unique_ptr<T> • Ownership semantics • Think auto_ptr<T> done right • Calls delete or delete[] in destructor • Movable, but not copyable (see Move Semantics later) • No runtime overhead #include <memory> std::unique_ptr<widget> getWidget(); void foo() { std::unique_ptr<widget> pw{ getWidget() }; // The widget is exclusively ours // We can’t accidentally share it // It will be deleted automatically and exception-safe }
  • 10. shared_ptr<T> • Ref-counting semantics shared_ptr<T> T • Last one calls delete in destructor • Transparent and deterministic shared_ptr<T> • Ref-counting and synchronization overhead • Use make_shared to reduce overhead shared_ptr<T> counter control block • Use weak_ptr to break cycles #include <memory> std::shared_ptr<widget> getWidget(); void foo() { std::shared_ptr<widget> pw{ getWidget() }; // The widget may be shared // We don’t own it so we don’t care about deleting it }
  • 11. Resource Acquisition is Initialization void f() { database *pdb = open_database("mydb"); … // What if we return or throw here? close_database(pdb); } class DBConnection { private: database *_pdb; public: explicit DBConnection(const char *name) : pdb(open_database(dbname)) {} ~DBConnection() { close_database(pdb); } } void f() { DBConnection dbc("mydb"); … // The db connection is guaranteed to close properly }
  • 12. Resource Acquisition is Initialization • GC in other languages only handles one resource - memory • RAII in C++ has been around for over a decade • C++11 encourages its use as default • Smart pointers help building RAII around legacy interfaces • Move semantics makes passing resources around cheap
  • 17. What’s wrong with low-level? • Unsafe? – Yes • Tedious? – Yes • Gets in the way of DRY? – Yes • Best performance? – No. May even make it worse Low-level programming is a powerful and complex tool, but it doesn’t guarantee you any advantage unless used properly.
  • 19. Value semantics as copy semantics • Value semantics traditionally means copy-semantics • Which means object gets copied when travels from one place to another • Which makes returning an object from a function expensive Matrix operator+( const Matrix& a, const Matrix& b ) { Matrix r; // Loop with r[i,j] = a[i,j]+b[i,j] return r; // Copying happens here – expensive } • Which requires ugly workarounds void operator+( const Matrix& a, const Matrix& b, Matrix& r ) { // Loop with r[i,j] = a[i,j]+b[i,j] }
  • 23. Move constructor (and =) template <typename T> class Matrix { private: unsigned int m; // Number of rows unsigned int n; // Number of columns T *pelems; // Pointer to an array of m*n elements public: … // Copy constructor Matrix( const Matrix& other ) : m(other.m), n(other.n) { pelems = new T[m*n]; memcpy( pelems, other.pelems, m*n*sizeof(T) ); } // Move constructor Matrix( Matrix&& other ) { pelems = other.pelems; other.pelems = nullptr; } ~Matrix(){ delete[] pelems; } };
  • 24. Move semantics Matrix m = a * transpose(b) + c * inv(d); • Readable • Efficient • Safe • Meaningful • Backward-compatible • Fully supported by STL
  • 25. Rvalue references Matrix( const Matrix& other ); // const lvalue ref Matrix( Matrix&& other ); // non-const rvalue ref • The right function is selected through overload resolution • Rvalue reference is preferred when called with rvalue • Non-constness of the rvalue reference allows to modify the rvalue • Bonus: perfect forwarding
  • 26. Copy or Move? • Implicit Matrix f( const Matrix& a ) { Matrix r(a); // copy: a can be used below, don’t mess with it … return r; // move: r is on its last leg } • Explicit Matrix f() { Matrix e{ {1,0}, {0,1} }; Matrix r( std::move(e) ); // forced move: e is zombie now and … // using it would be a bad idea }
  • 28. Life before lambdas #include <vector> #include <algorithm> #include <iostream> using namespace std; struct DivisibilityPredicateFunctor { int m_d; DivisibilityPredicate( int d ) : m_d(d) {} bool operator()( int n ) const { return n % m_d == 0; } }; void OutputFunction( int n ) { cout << n << endl; }; vector<int> remove_multiples( vector<int> v, int d ) { vector<int> r; remove_copy_if( begin(v), end(v), back_inserter(r), DivisibilityPredicateFunctor(d) ); return r; } void main() { vector<int> v; int array[] = {0,1,2,3,4,5,6,7,8,9}; for( int i = 0; i < sizeof array/sizeof *array; ++i ) v.push_back( array[i] ); vector<int> m = remove_multiples( v, 3 ); for_each( begin(m), end(m), OutputFunction ); }
  • 29. Life in C++11 #include <vector> #include <algorithm> #include <iostream> using namespace std; vector<int> remove_multiples( vector<int> v, int d ) { vector<int> r; remove_copy_if( begin(v), end(v), back_inserter(r), [=](int n){ return n % d == 0; } ); return r; } void main() { vector<int> m = remove_multiples( {0,1,2,3,4,5,6,7,8,9}, 3 ); for_each( begin(m), end(m), [](int n){ cout << n << endl; } ); }
  • 30. Lambdas • Without jumping through hoops now: – STL algorithms – Callbacks – Threading • Foundation for higher-level stuff: – Async programming – Functional programming C++ flavor: you have fine-grained control over environment capture.
  • 31. Lambda anatomy return type lambda introducer captured variable [=] (int n) -> int { return n % d == 0; } parameter list capture list body
  • 32. Lambda physiology • For each lambda compiler generates a class struct CompilerGeneratedFunctor { [d](int n)->bool int m_d; { CompilerGeneratedFunctor(int d) : m_d(d) {} bool operator()(int n) const return n % d == 0; { } return n % m_d == 0; } }; • Specifying lambda instantiates an object • Invoking lambda calls the object’s operator() • Everything is easily inlinable
  • 33. Lambda physiology • Lambda with empty capture list is just a function [](int n)->bool bool CompilerGeneratedFunction(int n) { { return n % 2 == 0; return n % 2 == 0; } } • Inlining is even easier
  • 34. Variable capture By value By reference Mix [=] [&] [=, &x, &y] [x, y, z] [&x, &y, &z] [&, x, y]