SlideShare une entreprise Scribd logo
1  sur  35
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
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]
 }
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

Contenu connexe

Tendances

[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...Francesco Casalegno
 
C++11 concurrency
C++11 concurrencyC++11 concurrency
C++11 concurrencyxu liwei
 
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 ForwardingFrancesco Casalegno
 
C++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabsC++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabsStephane Gleizes
 
Regular types in C++
Regular types in C++Regular types in C++
Regular types in C++Ilio Catallo
 
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
 
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
 
STL ALGORITHMS
STL ALGORITHMSSTL ALGORITHMS
STL ALGORITHMSfawzmasood
 
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
 
What's New in C++ 11/14?
What's New in C++ 11/14?What's New in C++ 11/14?
What's New in C++ 11/14?Dina Goldshtein
 
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays 2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays kinan keshkeh
 

Tendances (20)

C++11
C++11C++11
C++11
 
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
 
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 concurrency
C++11 concurrencyC++11 concurrency
C++11 concurrency
 
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
 
Smart Pointers in C++
Smart Pointers in C++Smart Pointers in C++
Smart Pointers in C++
 
The Style of C++ 11
The Style of C++ 11The Style of C++ 11
The Style of C++ 11
 
Le langage rust
Le langage rustLe langage rust
Le langage rust
 
Summary of C++17 features
Summary of C++17 featuresSummary of C++17 features
Summary of C++17 features
 
C++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabsC++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabs
 
Regular types in C++
Regular types in C++Regular types in C++
Regular types in C++
 
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)
 
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)
 
STL ALGORITHMS
STL ALGORITHMSSTL ALGORITHMS
STL ALGORITHMS
 
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]
 
What's New in C++ 11/14?
What's New in C++ 11/14?What's New in C++ 11/14?
What's New in C++ 11/14?
 
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays 2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
 

En vedette

Big data: The next frontier for innovation, competition, and productivity
Big data: The next frontier for innovation, competition, and productivityBig data: The next frontier for innovation, competition, and productivity
Big data: The next frontier for innovation, competition, and productivityMARAM SRAVAN KUMAR
 
The value of site testing
The value of site testing The value of site testing
The value of site testing AlexSpez
 
Satu hari di majlis hi
Satu hari di majlis hiSatu hari di majlis hi
Satu hari di majlis hiAzie Maskan
 
Anugerah allah yang tiada nilai bandingnya
Anugerah allah yang tiada nilai bandingnyaAnugerah allah yang tiada nilai bandingnya
Anugerah allah yang tiada nilai bandingnyaAzie Maskan
 
Taylor Root Salary Survey 2012 for West End, Niche and Boutique Law Firms
Taylor Root Salary Survey 2012 for West End, Niche and Boutique Law FirmsTaylor Root Salary Survey 2012 for West End, Niche and Boutique Law Firms
Taylor Root Salary Survey 2012 for West End, Niche and Boutique Law FirmsNickSmetana
 
a Case study on A V Birla Group - Legacy of Free Enterprise and Diversification
 a Case study on A V Birla Group - Legacy of Free Enterprise and Diversification a Case study on A V Birla Group - Legacy of Free Enterprise and Diversification
a Case study on A V Birla Group - Legacy of Free Enterprise and DiversificationMARAM SRAVAN KUMAR
 
Cjd may 19-25, 2012 post service calls
Cjd  may 19-25, 2012 post service callsCjd  may 19-25, 2012 post service calls
Cjd may 19-25, 2012 post service callsjaninabaluyot
 
ВШ 2014 Лекция №2 - Безопасность и ориентирование
ВШ 2014 Лекция №2 - Безопасность и ориентированиеВШ 2014 Лекция №2 - Безопасность и ориентирование
ВШ 2014 Лекция №2 - Безопасность и ориентированиеAlexander Korvyakov
 
Entreprenuer ship businessplan
Entreprenuer ship businessplanEntreprenuer ship businessplan
Entreprenuer ship businessplanMARAM SRAVAN KUMAR
 
Subhanallah, hamil itu menakjubkan!
Subhanallah, hamil itu menakjubkan!Subhanallah, hamil itu menakjubkan!
Subhanallah, hamil itu menakjubkan!Azie Maskan
 
ВШ 2014 - Лекция № 4 - "Валы, бочки, водопадные сливы" - Качанов
ВШ 2014 - Лекция № 4 - "Валы, бочки, водопадные сливы" - КачановВШ 2014 - Лекция № 4 - "Валы, бочки, водопадные сливы" - Качанов
ВШ 2014 - Лекция № 4 - "Валы, бочки, водопадные сливы" - КачановAlexander Korvyakov
 
ВШ 2014. Лекция №5 - Виды водных препятствий
ВШ 2014. Лекция №5 - Виды водных препятствийВШ 2014. Лекция №5 - Виды водных препятствий
ВШ 2014. Лекция №5 - Виды водных препятствийAlexander Korvyakov
 
ВШ 2014 - Лекция № 3 - типы судов. снаряжение для водного туризма
ВШ 2014 - Лекция № 3 - типы судов. снаряжение для водного туризмаВШ 2014 - Лекция № 3 - типы судов. снаряжение для водного туризма
ВШ 2014 - Лекция № 3 - типы судов. снаряжение для водного туризмаAlexander Korvyakov
 

En vedette (17)

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

Similaire à C++11: Feel the New Language

C++totural file
C++totural fileC++totural file
C++totural filehalaisumit
 
Options and trade offs for parallelism and concurrency in Modern C++
Options and trade offs for parallelism and concurrency in Modern C++Options and trade offs for parallelism and concurrency in Modern C++
Options and trade offs for parallelism and concurrency in Modern C++Satalia
 
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17LogeekNightUkraine
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++Manzoor ALam
 
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)PROIDEA
 
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Tudor Dragan
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupSyedHaroonShah4
 
C++tutorial
C++tutorialC++tutorial
C++tutorialdips17
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and DestructorsKeyur Vadodariya
 
SimpleArray between Python and C++
SimpleArray between Python and C++SimpleArray between Python and C++
SimpleArray between Python and C++Yung-Yu Chen
 
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docxeugeniadean34240
 
Addressing Scenario
Addressing ScenarioAddressing Scenario
Addressing ScenarioTara Hardin
 
Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)Brendan Eich
 

Similaire à C++11: Feel the New Language (20)

Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
C++totural file
C++totural fileC++totural file
C++totural file
 
C++ tutorial
C++ tutorialC++ tutorial
C++ tutorial
 
Clanguage
ClanguageClanguage
Clanguage
 
Options and trade offs for parallelism and concurrency in Modern C++
Options and trade offs for parallelism and concurrency in Modern C++Options and trade offs for parallelism and concurrency in Modern C++
Options and trade offs for parallelism and concurrency in Modern C++
 
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
 
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
 
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrup
 
C++tutorial
C++tutorialC++tutorial
C++tutorial
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
C
CC
C
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
Return of c++
Return of c++Return of c++
Return of c++
 
SimpleArray between Python and C++
SimpleArray between Python and C++SimpleArray between Python and C++
SimpleArray between Python and C++
 
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
 
Addressing Scenario
Addressing ScenarioAddressing Scenario
Addressing Scenario
 
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)
 
Writing MySQL UDFs
Writing MySQL UDFsWriting MySQL UDFs
Writing MySQL UDFs
 

Dernier

FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 

Dernier (20)

FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 

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
  • 14.
  • 15.
  • 16.
  • 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] }
  • 20.
  • 21.
  • 22.
  • 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]