SlideShare ist ein Scribd-Unternehmen logo
1 von 44
Return of
  C++
About Me
• Software architect in Intel since December 2005
• Focused on software design and network security before
  joining Intel
• ~28 years since writing my first program
   – Programming is fun!
• A casual open-source contributor
   – Several projects, but small contributions
   – Mostly on multi-lingual support (esp. Chinese)
• A happy father of twins
Programming languages are a
  fashion world. Languages
   come, languages go....
Do you know the August ’12
news in TIOBE Programming
    Community Index?
C++ dethroned from No. 3 …
           again
However, C++ is very much
active, having been active for
          ~30 years.
Aims of C++
• C++ makes programming more enjoyable for
  serious programmers.
• C++ is a general-purpose programming
  language that
  –   is a better C
  –   supports data abstraction
  –   supports object-oriented programming
  –   supports generic programming
Some C++ Design Rules
• C++’s evolution must be driven by real problems.
• C++ must be useful now.
• Don’t try to force people to use a specific programming
  style.
• It is more important to allow a useful feature than to
  prevent every misuse.
• Provide as good support for user-defined types as for built-
  in types.
• What you don’t use, you don’t pay for (zero overhead rule).
C++ is biased towards
systems programming, why
    is it popular also in
applications programming?
Reason for C++ in Applications
• Performance of a specialized language
• Multiple categories in a complex application
• Language mix issue
• C++ library capabilities
Better C++ Support Coming
• C++11 standardization
• C++ native binding in Windows Runtime
• C++ support to mix with Objective-C
• Better C++ support in Android NDK
• C++11 coming to MSVC, GCC, and Clang
Why the renaissance?
One word.
Mobile.
More words?
Performance/W
Performance/T
Performance/C

Performance/$
Good timing for the new
  C++11 standard....
Example
• How short can you get in C++ to dispatch
  work to a new thread and get the result in
  the current thread?
• Probably shorter than you expected:
     future<string> ft(async(...));
     ...
     cout << ft.get();
Example
string flip(string s)
{
    reverse(s.begin(), s.end());
    return s;
}

int main()
{
    vector<future<string>> v;

    v.push_back(async([] { return flip( " ,olleH"); }));
    v.push_back(async([] { return flip("n!letnI"); }));

    for (auto& e : v) {
        cout << e.get();
    }
}
Example
string flip(string s)
{
    reverse(s.begin(), s.end());
    return s;
}

int main()
{
    vector<future<string>> v;

    v.push_back(async([] { return flip( " ,olleH"); }));
    v.push_back(async([] { return flip("n!letnI"); }));

    for (auto& e : v) {
        cout << e.get();
    }
}
Example
string flip(string s)
{
    reverse(s.begin(), s.end());
    return s;
}

int main()
{
    vector<future<string>> v;

    v.push_back(async([] { return flip( " ,olleH"); }));
    v.push_back(async([] { return flip("n!letnI"); }));

    for (auto& e : v) {
        cout << e.get();
    }
}
Example
string flip(string s)
{
    reverse(s.begin(), s.end());
    return s;
}

int main()
{
    vector<future<string>> v;

    v.push_back(async([] { return flip( " ,olleH"); }));
    v.push_back(async([] { return flip("n!letnI"); }));

    for (auto& e : v) {
        cout << e.get();
    }
}
Compiler Compatibility
• Visual Studio 2012
  – Pass
• Clang 4.1 & libc++ (OS X)
  – Pass
• Visual Studio 2010
  – Range-based for and future are unsupported
• GCC 4.7.2; ICC 13.0.1 (on top of VS2010)
  – future is unsupported
Incomplete List of C++11 Features
•   Rvalue references and move semantics                    Performance
•   Initializer lists
•   Range-based for-loop
•   Type inference (auto)
•   Lambda functions and expressions                         Usability
•   Explicit overrides and final
•   Null pointer constant (nullptr)
•   Right angle brackets
•   Unicode characters and strings
•   Multi-threading memory model                           Functionality
•   Static assertions
•   Smart pointers and other standard library improvements
•   …
Rvalue References and Move Semantics

•   Sorry, it might be too complex for a one-pager…
•   Problem: copying objects (containers) can be expensive
•   Key concepts: object lifecycle, temporary, lvalue, rvalue
•   Key result: able to take away the object content in a
    reasonable and consistent way, without surprises, via
    – A new reference type (&&) and related rules
    – Utilities to convert a type to rvalue reference type (like std::move)
    – Move functions to move content to the new object and erase the
      original


• Demo of destructor elimination
Initializer Lists
• C++98 allows code like this:
      int array[] = { 1, 2, 3, 4 };
• C++11 now allows:
      vector<int> v = { 1, 2, 3, 4 };
• And you can initialize your own container this way:
      MyContainer::MyContainer(
              std::initializer_list<Type> list)
      {
          ...
      }
Range-based for-loop
• Example:
     for (int x : { 1, 1, 2, 3, 5 }) {
         cout << x << endl;
     }
• It implicitly calls begin() and end() on the
  list/array/container.
Type Inference
• Instead of writing:
     vector<boost::future<string> >
         ::iterator i = v.begin();


• One can now simply write:
     auto i = v.begin();
Lambdas
• Convenient where functors can be used
  – Say, for_each and transform
• Each lambda has a different type
  – So auto is handy
  – Class template std::function can be used to store
    lambdas
• Example:
     FILE* fp = fopen(...);
     ON_SCOPE_EXIT([&]() { fclose(fp); });
     ...
Explicit Overrides and Final
• Example
     struct Base {
         virtual void some(float);
         virtual void other();
     };
     struct Derived1 : Base {
         virtual void some(int) override;   // error
         virtual void other() final;
     };
     struct Derived2 : Derived1 {
         virtual void other(); // error
     };
Null Pointer Constant
• The definition of NULL causes surprises for:
     void foo(char*);
     void foo(int);
     ...
     foo(NULL);
• Now foo(nullptr) correctly calls
  foo(char*).
Right Angle Brackets
• C++98 requires an extra space here:
     vector<list<string> > sv;


• C++11 allows people to write:
     vector<list<string>> sv;
Unicode Characters and Strings
• Example:
    char n[] = "GCC and MSVC encode
 differently: u2018.";
    wchar_t w[] = L"Is it 16-bit or 32-bit:
 u2018?";

    char a[] = u8"UTF-8 string: u2018.";
    char16_t b[] = u"UTF-16 string: u2018.";
    char32_t c[] = U"UTF-32 string: u2018.";
Multi-Threading Memory Model
• Another complex topic
• Memory model is defined
• Standard library facilities:
  – Mutexes, conditional variables, RAII locks
  – Futures and promises (first example)
  – Atomic operations
Static Assertions
• Example:
    template<class T>
    struct Check {
        static_assert(sizeof(int) <= sizeof(T),
            "T is not big enough!");
    };

    void DoSomething(...)
    {
        static_assert(sizeof(void*) == 4,
          "Supports only 32-bit platforms");
        ...
    }
Smart Pointers
• Example:
    unique_ptr<int> p1(new int(5));
    unique_ptr<int> p2 = p1; // compile error
    unique_ptr<int> p3 = move(p1); // transfers ownership.
    p3.reset(); // deletes the memory.
    p1.reset(); // does nothing.

    shared_ptr<int> p1(new int(5)); // refcount = 1
    shared_ptr<int> p2 = p1; // refcount = 2
    p1.reset(); // refcount = 1
    p2.reset(); // refcount = 0; frees memory
Summary
• Mobile and cloud make C++ relevant again.
• The new C++11 standard makes C++ a more
  powerful but easier-to-use language.
  – Definitely worth adopting
  – Especially for application developers
• Today is just an introduction.
References
•   ISO/IEC JTC 1/SC22: N3337 – Draft C++ Standard (very close to C++11)
•   Bjarne Stroustrup: Evolving a language in and for the real world: C++ 1991-2006
•   Bjarne Stroustrup: An Overview of the C++ Programming Language
•   Scott Meyers: Summary of C++11 Feature Availability in gcc and MSVC
•   Wikipedia: C++11
•   刘未鹏: C++11 (及现代C++风格)和快速迭代式开发
•   Stephan T. Lavavej: Lambdas, auto, and static_assert: C++0x Features in VC10, Part 1
•   Stephan T. Lavavej: Rvalue References: C++0x Features in VC10, Part 2
•   Stephan T. Lavavej: decltype: C++0x Features in VC10, Part 3
•   Thomas Becker: C++ Rvalue References Explained
•   Herb Sutter: C++ and Beyond 2011: Herb Sutter - Why C++?
•   Andrei Alexandrescu, Scott Meyers, Herb Sutter: On Static If, C++11 in 2012, Modern
    Libraries, and Metaprogramming
•   Nicolai M. Josuttis: The C++ Standard Library: A Tutorial and Reference (2nd Edition).
    Addison-Wesley, 2012
Backup
Poor Man’s Future – Option 1
static string tmp1() { return flip( " ,olleH"); }
static string tmp2() { return flip("n!letnI"); }

int main()
{
    vector<boost::future<string>> v;

    v.push_back(boost::async(tmp1));
    v.push_back(boost::async(tmp2));

    for (auto i = v.begin(); i != v.end(); ++i) {
        cout << i->get();
    }
}
Poor Man’s Future – Option 2
int main()
{
    vector<boost::future<string>> v;

    { boost::packaged_task<string> pt([]
        { return flip( " ,olleH"); });
      v.push_back(pt.get_future());
      boost::thread task(boost::move(pt)); }
    { boost::packaged_task<string> pt([]
        { return flip("n!letnI"); });
      v.push_back(pt.get_future());
      boost::thread task(boost::move(pt)); }

    for (auto i = v.begin(); i != v.end(); ++i) {
        cout << i->get();
    }
}
Use Boost with MSVC
• Most of Boost can be used without building
• One needs to add the include path BOOST
   – For IDE: Tools > Options > Projects > VC++ Directories > Include files
   – For command line: the environment variable INCLUDE
• Some components need building, like the unit test
  framework
   b2 toolset=msvc-10.0 --with-test debug link=static runtime-
     link=static stage
   b2 toolset=msvc-10.0 --with-chrono --with-date_time --with-
     system --with-thread debug release link=static runtime-
     link=static stage
• One then needs to add the library path BOOSTstagelib
   – For IDE: Tools > Options > Projects > VC++ Directories > Library files
   – For command line: the environment variable LIB

Weitere ähnliche Inhalte

Was ist angesagt?

Virtual machine and javascript engine
Virtual machine and javascript engineVirtual machine and javascript engine
Virtual machine and javascript engineDuoyi Wu
 
Concurrency Concepts in Java
Concurrency Concepts in JavaConcurrency Concepts in Java
Concurrency Concepts in JavaDoug Hawkins
 
Introduction to Rust language programming
Introduction to Rust language programmingIntroduction to Rust language programming
Introduction to Rust language programmingRodolfo Finochietti
 
An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...Claudio Capobianco
 
Asynchronous single page applications without a line of HTML or Javascript, o...
Asynchronous single page applications without a line of HTML or Javascript, o...Asynchronous single page applications without a line of HTML or Javascript, o...
Asynchronous single page applications without a line of HTML or Javascript, o...Robert Schadek
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsBartosz Kosarzycki
 
Kotlin in action
Kotlin in actionKotlin in action
Kotlin in actionCiro Rizzo
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?Doug Hawkins
 
[2019-07] GraphQL in depth (serverside)
[2019-07] GraphQL in depth (serverside)[2019-07] GraphQL in depth (serverside)
[2019-07] GraphQL in depth (serverside)croquiscom
 
The Ring programming language version 1.2 book - Part 79 of 84
The Ring programming language version 1.2 book - Part 79 of 84The Ring programming language version 1.2 book - Part 79 of 84
The Ring programming language version 1.2 book - Part 79 of 84Mahmoud Samir Fayed
 
Skiron - Experiments in CPU Design in D
Skiron - Experiments in CPU Design in DSkiron - Experiments in CPU Design in D
Skiron - Experiments in CPU Design in DMithun Hunsur
 
Tips and tricks for building high performance android apps using native code
Tips and tricks for building high performance android apps using native codeTips and tricks for building high performance android apps using native code
Tips and tricks for building high performance android apps using native codeKenneth Geisshirt
 
(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your Groovy(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your GroovyAlonso Torres
 
HexRaysCodeXplorer: make object-oriented RE easier
HexRaysCodeXplorer: make object-oriented RE easierHexRaysCodeXplorer: make object-oriented RE easier
HexRaysCodeXplorer: make object-oriented RE easierAlex Matrosov
 
HexRaysCodeXplorer: object oriented RE for fun and profit
HexRaysCodeXplorer: object oriented RE for fun and profitHexRaysCodeXplorer: object oriented RE for fun and profit
HexRaysCodeXplorer: object oriented RE for fun and profitAlex Matrosov
 
clWrap: Nonsense free control of your GPU
clWrap: Nonsense free control of your GPUclWrap: Nonsense free control of your GPU
clWrap: Nonsense free control of your GPUJohn Colvin
 
C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012 C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012 Sumant Tambe
 
Java Keeps Throttling Up!
Java Keeps Throttling Up!Java Keeps Throttling Up!
Java Keeps Throttling Up!José Paumard
 
iOS Development with Blocks
iOS Development with BlocksiOS Development with Blocks
iOS Development with BlocksJeff Kelley
 

Was ist angesagt? (20)

Virtual machine and javascript engine
Virtual machine and javascript engineVirtual machine and javascript engine
Virtual machine and javascript engine
 
Concurrency Concepts in Java
Concurrency Concepts in JavaConcurrency Concepts in Java
Concurrency Concepts in Java
 
Introduction to Rust language programming
Introduction to Rust language programmingIntroduction to Rust language programming
Introduction to Rust language programming
 
Why rust?
Why rust?Why rust?
Why rust?
 
An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...
 
Asynchronous single page applications without a line of HTML or Javascript, o...
Asynchronous single page applications without a line of HTML or Javascript, o...Asynchronous single page applications without a line of HTML or Javascript, o...
Asynchronous single page applications without a line of HTML or Javascript, o...
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
 
Kotlin in action
Kotlin in actionKotlin in action
Kotlin in action
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
 
[2019-07] GraphQL in depth (serverside)
[2019-07] GraphQL in depth (serverside)[2019-07] GraphQL in depth (serverside)
[2019-07] GraphQL in depth (serverside)
 
The Ring programming language version 1.2 book - Part 79 of 84
The Ring programming language version 1.2 book - Part 79 of 84The Ring programming language version 1.2 book - Part 79 of 84
The Ring programming language version 1.2 book - Part 79 of 84
 
Skiron - Experiments in CPU Design in D
Skiron - Experiments in CPU Design in DSkiron - Experiments in CPU Design in D
Skiron - Experiments in CPU Design in D
 
Tips and tricks for building high performance android apps using native code
Tips and tricks for building high performance android apps using native codeTips and tricks for building high performance android apps using native code
Tips and tricks for building high performance android apps using native code
 
(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your Groovy(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your Groovy
 
HexRaysCodeXplorer: make object-oriented RE easier
HexRaysCodeXplorer: make object-oriented RE easierHexRaysCodeXplorer: make object-oriented RE easier
HexRaysCodeXplorer: make object-oriented RE easier
 
HexRaysCodeXplorer: object oriented RE for fun and profit
HexRaysCodeXplorer: object oriented RE for fun and profitHexRaysCodeXplorer: object oriented RE for fun and profit
HexRaysCodeXplorer: object oriented RE for fun and profit
 
clWrap: Nonsense free control of your GPU
clWrap: Nonsense free control of your GPUclWrap: Nonsense free control of your GPU
clWrap: Nonsense free control of your GPU
 
C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012 C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012
 
Java Keeps Throttling Up!
Java Keeps Throttling Up!Java Keeps Throttling Up!
Java Keeps Throttling Up!
 
iOS Development with Blocks
iOS Development with BlocksiOS Development with Blocks
iOS Development with Blocks
 

Andere mochten auch

Lenguajesdeprogramacion c nivel1-unidad1-03-funciones definidas por el usuario
Lenguajesdeprogramacion c nivel1-unidad1-03-funciones definidas por el usuarioLenguajesdeprogramacion c nivel1-unidad1-03-funciones definidas por el usuario
Lenguajesdeprogramacion c nivel1-unidad1-03-funciones definidas por el usuarioCarlos
 
Estructuras de repetición (1)
Estructuras de repetición (1)Estructuras de repetición (1)
Estructuras de repetición (1)Fredy Torres
 
Programacion en C++ para Ciencia e Ingeniería
Programacion en C++ para Ciencia e IngenieríaProgramacion en C++ para Ciencia e Ingeniería
Programacion en C++ para Ciencia e IngenieríaStorti Mario
 
Diagramas de flujo - Estructuras de Control (For, While, Do Whille y Switch C...
Diagramas de flujo - Estructuras de Control (For, While, Do Whille y Switch C...Diagramas de flujo - Estructuras de Control (For, While, Do Whille y Switch C...
Diagramas de flujo - Estructuras de Control (For, While, Do Whille y Switch C...Marcelo Vilela Pardo
 
Diagrama de Flujos Ejemplos.
Diagrama de Flujos Ejemplos.Diagrama de Flujos Ejemplos.
Diagrama de Flujos Ejemplos.luismarlmg
 
Estructuras de repetición en programacion
Estructuras de repetición en programacionEstructuras de repetición en programacion
Estructuras de repetición en programacionSERCOMPFAST
 
Estructuras repetitivas - pseudocodigo
Estructuras repetitivas - pseudocodigoEstructuras repetitivas - pseudocodigo
Estructuras repetitivas - pseudocodigoRosbelia Balza
 

Andere mochten auch (8)

Lenguajesdeprogramacion c nivel1-unidad1-03-funciones definidas por el usuario
Lenguajesdeprogramacion c nivel1-unidad1-03-funciones definidas por el usuarioLenguajesdeprogramacion c nivel1-unidad1-03-funciones definidas por el usuario
Lenguajesdeprogramacion c nivel1-unidad1-03-funciones definidas por el usuario
 
Estructuras de repetición (1)
Estructuras de repetición (1)Estructuras de repetición (1)
Estructuras de repetición (1)
 
Programacion en C++ para Ciencia e Ingeniería
Programacion en C++ para Ciencia e IngenieríaProgramacion en C++ para Ciencia e Ingeniería
Programacion en C++ para Ciencia e Ingeniería
 
Diagramas De Flujo
Diagramas De FlujoDiagramas De Flujo
Diagramas De Flujo
 
Diagramas de flujo - Estructuras de Control (For, While, Do Whille y Switch C...
Diagramas de flujo - Estructuras de Control (For, While, Do Whille y Switch C...Diagramas de flujo - Estructuras de Control (For, While, Do Whille y Switch C...
Diagramas de flujo - Estructuras de Control (For, While, Do Whille y Switch C...
 
Diagrama de Flujos Ejemplos.
Diagrama de Flujos Ejemplos.Diagrama de Flujos Ejemplos.
Diagrama de Flujos Ejemplos.
 
Estructuras de repetición en programacion
Estructuras de repetición en programacionEstructuras de repetición en programacion
Estructuras de repetición en programacion
 
Estructuras repetitivas - pseudocodigo
Estructuras repetitivas - pseudocodigoEstructuras repetitivas - pseudocodigo
Estructuras repetitivas - pseudocodigo
 

Ähnlich wie Return of c++

Modern C++ Lunch and Learn
Modern C++ Lunch and LearnModern C++ Lunch and Learn
Modern C++ Lunch and LearnPaul Irwin
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.pptDevliNeeraj
 
ESL Anyone?
ESL Anyone? ESL Anyone?
ESL Anyone? DVClub
 
[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...
[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...
[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...Sang Don Kim
 
Cs1123 11 pointers
Cs1123 11 pointersCs1123 11 pointers
Cs1123 11 pointersTAlha MAlik
 
Memory Management with Java and C++
Memory Management with Java and C++Memory Management with Java and C++
Memory Management with Java and C++Mohammad Shaker
 
2 BytesC++ course_2014_c1_basicsc++
2 BytesC++ course_2014_c1_basicsc++2 BytesC++ course_2014_c1_basicsc++
2 BytesC++ course_2014_c1_basicsc++kinan keshkeh
 
Abhishek lingineni
Abhishek lingineniAbhishek lingineni
Abhishek lingineniabhishekl404
 
CPlusPus
CPlusPusCPlusPus
CPlusPusrasen58
 
Programming Languages: some news for the last N years
Programming Languages: some news for the last N yearsProgramming Languages: some news for the last N years
Programming Languages: some news for the last N yearsRuslan Shevchenko
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overviewTAlha MAlik
 
C++_programs.ppt
C++_programs.pptC++_programs.ppt
C++_programs.pptTeacherOnat
 

Ähnlich wie Return of c++ (20)

Modern C++
Modern C++Modern C++
Modern C++
 
Modern C++ Lunch and Learn
Modern C++ Lunch and LearnModern C++ Lunch and Learn
Modern C++ Lunch and Learn
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
ESL Anyone?
ESL Anyone? ESL Anyone?
ESL Anyone?
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
c++ ppt.ppt
c++ ppt.pptc++ ppt.ppt
c++ ppt.ppt
 
[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...
[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...
[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...
 
Cs1123 11 pointers
Cs1123 11 pointersCs1123 11 pointers
Cs1123 11 pointers
 
Memory Management with Java and C++
Memory Management with Java and C++Memory Management with Java and C++
Memory Management with Java and C++
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
2 BytesC++ course_2014_c1_basicsc++
2 BytesC++ course_2014_c1_basicsc++2 BytesC++ course_2014_c1_basicsc++
2 BytesC++ course_2014_c1_basicsc++
 
Abhishek lingineni
Abhishek lingineniAbhishek lingineni
Abhishek lingineni
 
CPlusPus
CPlusPusCPlusPus
CPlusPus
 
Programming Languages: some news for the last N years
Programming Languages: some news for the last N yearsProgramming Languages: some news for the last N years
Programming Languages: some news for the last N years
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
 
C++_programs.ppt
C++_programs.pptC++_programs.ppt
C++_programs.ppt
 
C++_programs.ppt
C++_programs.pptC++_programs.ppt
C++_programs.ppt
 

Return of c++

  • 1. Return of C++
  • 2. About Me • Software architect in Intel since December 2005 • Focused on software design and network security before joining Intel • ~28 years since writing my first program – Programming is fun! • A casual open-source contributor – Several projects, but small contributions – Mostly on multi-lingual support (esp. Chinese) • A happy father of twins
  • 3. Programming languages are a fashion world. Languages come, languages go....
  • 4. Do you know the August ’12 news in TIOBE Programming Community Index?
  • 5. C++ dethroned from No. 3 … again
  • 6.
  • 7. However, C++ is very much active, having been active for ~30 years.
  • 8. Aims of C++ • C++ makes programming more enjoyable for serious programmers. • C++ is a general-purpose programming language that – is a better C – supports data abstraction – supports object-oriented programming – supports generic programming
  • 9. Some C++ Design Rules • C++’s evolution must be driven by real problems. • C++ must be useful now. • Don’t try to force people to use a specific programming style. • It is more important to allow a useful feature than to prevent every misuse. • Provide as good support for user-defined types as for built- in types. • What you don’t use, you don’t pay for (zero overhead rule).
  • 10. C++ is biased towards systems programming, why is it popular also in applications programming?
  • 11. Reason for C++ in Applications • Performance of a specialized language • Multiple categories in a complex application • Language mix issue • C++ library capabilities
  • 12. Better C++ Support Coming • C++11 standardization • C++ native binding in Windows Runtime • C++ support to mix with Objective-C • Better C++ support in Android NDK • C++11 coming to MSVC, GCC, and Clang
  • 18.
  • 19. Good timing for the new C++11 standard....
  • 20. Example • How short can you get in C++ to dispatch work to a new thread and get the result in the current thread? • Probably shorter than you expected: future<string> ft(async(...)); ... cout << ft.get();
  • 21. Example string flip(string s) { reverse(s.begin(), s.end()); return s; } int main() { vector<future<string>> v; v.push_back(async([] { return flip( " ,olleH"); })); v.push_back(async([] { return flip("n!letnI"); })); for (auto& e : v) { cout << e.get(); } }
  • 22. Example string flip(string s) { reverse(s.begin(), s.end()); return s; } int main() { vector<future<string>> v; v.push_back(async([] { return flip( " ,olleH"); })); v.push_back(async([] { return flip("n!letnI"); })); for (auto& e : v) { cout << e.get(); } }
  • 23. Example string flip(string s) { reverse(s.begin(), s.end()); return s; } int main() { vector<future<string>> v; v.push_back(async([] { return flip( " ,olleH"); })); v.push_back(async([] { return flip("n!letnI"); })); for (auto& e : v) { cout << e.get(); } }
  • 24. Example string flip(string s) { reverse(s.begin(), s.end()); return s; } int main() { vector<future<string>> v; v.push_back(async([] { return flip( " ,olleH"); })); v.push_back(async([] { return flip("n!letnI"); })); for (auto& e : v) { cout << e.get(); } }
  • 25. Compiler Compatibility • Visual Studio 2012 – Pass • Clang 4.1 & libc++ (OS X) – Pass • Visual Studio 2010 – Range-based for and future are unsupported • GCC 4.7.2; ICC 13.0.1 (on top of VS2010) – future is unsupported
  • 26. Incomplete List of C++11 Features • Rvalue references and move semantics Performance • Initializer lists • Range-based for-loop • Type inference (auto) • Lambda functions and expressions Usability • Explicit overrides and final • Null pointer constant (nullptr) • Right angle brackets • Unicode characters and strings • Multi-threading memory model Functionality • Static assertions • Smart pointers and other standard library improvements • …
  • 27. Rvalue References and Move Semantics • Sorry, it might be too complex for a one-pager… • Problem: copying objects (containers) can be expensive • Key concepts: object lifecycle, temporary, lvalue, rvalue • Key result: able to take away the object content in a reasonable and consistent way, without surprises, via – A new reference type (&&) and related rules – Utilities to convert a type to rvalue reference type (like std::move) – Move functions to move content to the new object and erase the original • Demo of destructor elimination
  • 28. Initializer Lists • C++98 allows code like this: int array[] = { 1, 2, 3, 4 }; • C++11 now allows: vector<int> v = { 1, 2, 3, 4 }; • And you can initialize your own container this way: MyContainer::MyContainer( std::initializer_list<Type> list) { ... }
  • 29. Range-based for-loop • Example: for (int x : { 1, 1, 2, 3, 5 }) { cout << x << endl; } • It implicitly calls begin() and end() on the list/array/container.
  • 30. Type Inference • Instead of writing: vector<boost::future<string> > ::iterator i = v.begin(); • One can now simply write: auto i = v.begin();
  • 31. Lambdas • Convenient where functors can be used – Say, for_each and transform • Each lambda has a different type – So auto is handy – Class template std::function can be used to store lambdas • Example: FILE* fp = fopen(...); ON_SCOPE_EXIT([&]() { fclose(fp); }); ...
  • 32. Explicit Overrides and Final • Example struct Base { virtual void some(float); virtual void other(); }; struct Derived1 : Base { virtual void some(int) override; // error virtual void other() final; }; struct Derived2 : Derived1 { virtual void other(); // error };
  • 33. Null Pointer Constant • The definition of NULL causes surprises for: void foo(char*); void foo(int); ... foo(NULL); • Now foo(nullptr) correctly calls foo(char*).
  • 34. Right Angle Brackets • C++98 requires an extra space here: vector<list<string> > sv; • C++11 allows people to write: vector<list<string>> sv;
  • 35. Unicode Characters and Strings • Example: char n[] = "GCC and MSVC encode differently: u2018."; wchar_t w[] = L"Is it 16-bit or 32-bit: u2018?"; char a[] = u8"UTF-8 string: u2018."; char16_t b[] = u"UTF-16 string: u2018."; char32_t c[] = U"UTF-32 string: u2018.";
  • 36. Multi-Threading Memory Model • Another complex topic • Memory model is defined • Standard library facilities: – Mutexes, conditional variables, RAII locks – Futures and promises (first example) – Atomic operations
  • 37. Static Assertions • Example: template<class T> struct Check { static_assert(sizeof(int) <= sizeof(T), "T is not big enough!"); }; void DoSomething(...) { static_assert(sizeof(void*) == 4, "Supports only 32-bit platforms"); ... }
  • 38. Smart Pointers • Example: unique_ptr<int> p1(new int(5)); unique_ptr<int> p2 = p1; // compile error unique_ptr<int> p3 = move(p1); // transfers ownership. p3.reset(); // deletes the memory. p1.reset(); // does nothing. shared_ptr<int> p1(new int(5)); // refcount = 1 shared_ptr<int> p2 = p1; // refcount = 2 p1.reset(); // refcount = 1 p2.reset(); // refcount = 0; frees memory
  • 39. Summary • Mobile and cloud make C++ relevant again. • The new C++11 standard makes C++ a more powerful but easier-to-use language. – Definitely worth adopting – Especially for application developers • Today is just an introduction.
  • 40. References • ISO/IEC JTC 1/SC22: N3337 – Draft C++ Standard (very close to C++11) • Bjarne Stroustrup: Evolving a language in and for the real world: C++ 1991-2006 • Bjarne Stroustrup: An Overview of the C++ Programming Language • Scott Meyers: Summary of C++11 Feature Availability in gcc and MSVC • Wikipedia: C++11 • 刘未鹏: C++11 (及现代C++风格)和快速迭代式开发 • Stephan T. Lavavej: Lambdas, auto, and static_assert: C++0x Features in VC10, Part 1 • Stephan T. Lavavej: Rvalue References: C++0x Features in VC10, Part 2 • Stephan T. Lavavej: decltype: C++0x Features in VC10, Part 3 • Thomas Becker: C++ Rvalue References Explained • Herb Sutter: C++ and Beyond 2011: Herb Sutter - Why C++? • Andrei Alexandrescu, Scott Meyers, Herb Sutter: On Static If, C++11 in 2012, Modern Libraries, and Metaprogramming • Nicolai M. Josuttis: The C++ Standard Library: A Tutorial and Reference (2nd Edition). Addison-Wesley, 2012
  • 42. Poor Man’s Future – Option 1 static string tmp1() { return flip( " ,olleH"); } static string tmp2() { return flip("n!letnI"); } int main() { vector<boost::future<string>> v; v.push_back(boost::async(tmp1)); v.push_back(boost::async(tmp2)); for (auto i = v.begin(); i != v.end(); ++i) { cout << i->get(); } }
  • 43. Poor Man’s Future – Option 2 int main() { vector<boost::future<string>> v; { boost::packaged_task<string> pt([] { return flip( " ,olleH"); }); v.push_back(pt.get_future()); boost::thread task(boost::move(pt)); } { boost::packaged_task<string> pt([] { return flip("n!letnI"); }); v.push_back(pt.get_future()); boost::thread task(boost::move(pt)); } for (auto i = v.begin(); i != v.end(); ++i) { cout << i->get(); } }
  • 44. Use Boost with MSVC • Most of Boost can be used without building • One needs to add the include path BOOST – For IDE: Tools > Options > Projects > VC++ Directories > Include files – For command line: the environment variable INCLUDE • Some components need building, like the unit test framework b2 toolset=msvc-10.0 --with-test debug link=static runtime- link=static stage b2 toolset=msvc-10.0 --with-chrono --with-date_time --with- system --with-thread debug release link=static runtime- link=static stage • One then needs to add the library path BOOSTstagelib – For IDE: Tools > Options > Projects > VC++ Directories > Library files – For command line: the environment variable LIB

Hinweis der Redaktion

  1. Apart from C++, let people notice Objective-C,PHP, Python, Perl, and Ruby.
  2. According to Bjarne…
  3. Objective-C++: 2002Android support for C++ exceptions: NDK 5 (2010); shared C++ runtime w/ exceptions: NDK 7 (2011)
  4. Many features rely on standard libraries too.The standard library definition is about 70% of the normative text of the standard…
  5. Not supported by MSVC up to Visual Studio 2012
  6. As of Boost 1.52.0.
  7. As of Boost 1.52.0.