Glimpses of C++0x


Published on

This is Work-In-Progress. Developing a series of lectures on C++0x. This will augment my presentations on C++ and Design Pattern. First trial run was done at Interra, Noida in 2009

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • Maintain stability and compatibility don't break old code, and if you absolutely must, don't break it quietly. Prefer libraries to language extensions an ideal at which the committee wasn't all that successful; too many people in the committee and elsewhere prefer "real language features." Prefer generality to specialization focus on improving the abstraction mechanisms (classes, templates, etc.). Support both experts and novices novices can be helped by better libraries and through more general rules; experts need general and efficient features. Increase type safety primarily though facilities that allow programmers to avoid type-unsafe features. Improve performance and ability to work directly with hardware make C++ even better for embedded systems programming and high-performance computation. Fit into the real world consider tool chains, implementation cost, transition problems, ABI issues, teaching and learning, etc.
  • auto earlier was a storage class specifier for automatic variables.
  • The expression ((T)0) is a hackish way to write an expression that has the type T and doesn’t require T to be default constructible.
  • auto earlier was a storage class specifier for automatic variables.
  • auto earlier was a storage class specifier for automatic variables.
  • auto earlier was a storage class specifier for automatic variables.
  • Src: [N1377] A Proposal to Add Move Semantics Support to the C++ Language.mht
  • Glimpses of C++0x

    1. 1. December, 2009 Glimpses of C++0x Dr. Partha Pratim Das Interra Systems (India) Pvt. Ltd. Language Features
    2. 2. Agenda <ul><li>What is C++0x? </li></ul><ul><li>Select Language Features </li></ul>
    3. 3. What is C++0x? Basics
    4. 4. What is C++0x? <ul><li>C++0x is the next ISO C++ standard. </li></ul><ul><li>Current C++ standard is referred to as C++98 (C++03) </li></ul><ul><li>Current C standard is referred to as C99 </li></ul><ul><li>Current C++0x draft is SC22-N-4411.pdf. It comprises: </li></ul><ul><ul><li>Language Features </li></ul></ul><ul><ul><li>Standard Library Enhancements </li></ul></ul><ul><li>Expected to be ready for national votes in 2010. </li></ul><ul><li>After that another 18 month before ISO signs up. </li></ul><ul><li>No features are expected to be added or removed after March 2010. </li></ul><ul><li>The name &quot;C++0x&quot; is a relict of the hope for a C++08 or C++09. Now we should think of 'x' as hexadecimal. </li></ul>
    5. 5. Who decides on C++0x? <ul><li>ISO Standards committee, SC22 WG21. </li></ul><ul><li>Committee meets 2/3 times a year for a week each time. </li></ul><ul><li>Countries have national standards bodies with C++ groups. </li></ul><ul><ul><li>Active – Canada, France, Germany, Switzerland, UK, and USA. </li></ul></ul><ul><ul><li>Less Active – Denmark, the Netherlands, Japan, Norway, Spain. </li></ul></ul><ul><li>Work goes on offline and recorded as committee papers on the WG21 website. </li></ul><ul><li>There are sub-working groups, such as &quot;Core&quot;, &quot;Library&quot;, &quot;Evolution&quot;, and &quot;Concurrency.&quot; </li></ul><ul><li>The Main committee as a whole votes (one member one vote) and if something is accepted the nations vote. </li></ul><ul><li>The committee has formal liaison with the C standards group (SC22 WG14), POSIX, and several other groups. </li></ul>
    6. 6. What are the aims of C++0x? <ul><li>C++ is a general-purpose programming language with a bias towards systems programming that </li></ul><ul><ul><li>is a better C </li></ul></ul><ul><ul><li>supports data abstraction </li></ul></ul><ul><ul><li>supports object-oriented programming </li></ul></ul><ul><ul><li>supports generic programming </li></ul></ul>
    7. 7. What are the aims of C++0x? <ul><li>Make C++ a better language for systems programming and library building </li></ul><ul><ul><li>Avoid providing specialized facilities (e.g. numeric computation or Windows-style application development). </li></ul></ul><ul><li>Make C++ easier to teach and learn </li></ul><ul><ul><li>Through increased uniformity, stronger guarantees, and facilities supportive of novices </li></ul></ul><ul><li>Maintain very stringent compatibility constraints. </li></ul><ul><ul><li>Only very rarely break standards conforming code, though that's done when a new keyword (e.g. static_assert, nullptr, and constexpr) is introduced. </li></ul></ul>
    8. 8. What are the design goals of C++0x? <ul><li>Maintain stability and compatibility </li></ul><ul><li>Prefer libraries to language extensions </li></ul><ul><li>Prefer generality to specialization </li></ul><ul><li>Support both experts and novices </li></ul><ul><li>Increase type safety </li></ul><ul><li>Improve performance and ability to work directly with hardware </li></ul><ul><li>Fit into the real world </li></ul>
    9. 9. What are the design goals of C++0x? <ul><li>Systems programming </li></ul><ul><ul><li>improve the support for close-to-the-hardware programming (e.g. low-level embedded systems programming) and efficiency. </li></ul></ul><ul><ul><li>Examples are constexpr, std::array, and generalized PODs. </li></ul></ul><ul><li>Generic programming </li></ul><ul><ul><li>GP is among the great success stories of C++98; we needed to improve support for it based on experience. </li></ul></ul><ul><ul><li>Examples are auto and template aliases. </li></ul></ul><ul><li>Machine model and concurrency </li></ul><ul><ul><li>provide stronger guarantees for and better facilities for using modern hardware (e.g. multicores and weakly coherent memory models). </li></ul></ul><ul><ul><li>Examples are the thread ABI, thread-local storage, and the atomics ABI. </li></ul></ul><ul><li>Library building </li></ul><ul><ul><li>remove limitations, inefficiencies, and irregularities from the abstraction mechanisms. </li></ul></ul><ul><ul><li>Examples are inline namespace, inherited constructors, and rvalue references. </li></ul></ul>
    10. 10. C++0x: Language Features <ul><li>__cplusplus </li></ul><ul><li>alignments </li></ul><ul><li>attributes </li></ul><ul><li>atomic operations </li></ul><ul><li>auto </li></ul><ul><li>C99 features </li></ul><ul><li>enum class </li></ul><ul><li>copying and rethrowing exceptions </li></ul><ul><li>constant expressions </li></ul><ul><li>decltype </li></ul><ul><li>defaulted and deleted functions </li></ul><ul><li>delegating constructors </li></ul><ul><li>Dynamic Initialization and Destruction with Concurrency </li></ul><ul><li>explicit conversion operators </li></ul><ul><li>extended integer types </li></ul><ul><li>extern templates </li></ul><ul><li>for statement; see range for statement </li></ul><ul><li>suffix return type syntax (extended function declaration syntax) </li></ul><ul><li>in-class member initializers </li></ul><ul><li>inherited constructors </li></ul><ul><li>initializer lists (uniform and general initialization) </li></ul><ul><li>lambdas </li></ul>
    11. 11. C++0x: Language Features <ul><li>local classes as template arguments </li></ul><ul><li>long long integers </li></ul><ul><li>memory model </li></ul><ul><li>move semantics; see rvalue references </li></ul><ul><li>Inline namespace </li></ul><ul><li>Preventing narrowing </li></ul><ul><li>null pointer (nullptr) </li></ul><ul><li>PODs (generalized) </li></ul><ul><li>range for statement </li></ul><ul><li>raw string literals </li></ul><ul><li>right-angle brackets </li></ul><ul><li>rvalue references </li></ul><ul><li>Simple SFINAE (Substitution Failure Is Not An Error) rule </li></ul><ul><li>static (compile-time) assertions (static_assert) </li></ul><ul><li>template alias </li></ul><ul><li>template typedef; see template alias </li></ul><ul><li>thread-local storage (thread_local) </li></ul><ul><li>unicode characters </li></ul><ul><li>Uniform initialization syntax and semantics </li></ul><ul><li>unions (generalized) </li></ul><ul><li>user-defined literals </li></ul><ul><li>variadic templates </li></ul>
    12. 12. C++0x: Standard Library <ul><li>abandoning a process </li></ul><ul><li>Improvements to algorithms </li></ul><ul><li>array </li></ul><ul><li>async() </li></ul><ul><li>atomic operations </li></ul><ul><li>Condition variables </li></ul><ul><li>Improvements to containers </li></ul><ul><li>function and bind </li></ul><ul><li>forward_list (a singly-liked list) </li></ul><ul><li>future and promise </li></ul><ul><li>garbage collection ABI </li></ul><ul><li>hash_tables (unordered_map) </li></ul><ul><li>metaprogramming and type traits </li></ul><ul><li>Mutual exclusion </li></ul><ul><li>random number generators </li></ul><ul><li>regex (regular expression library) </li></ul><ul><li>scoped allocators </li></ul><ul><li>shared_ptr </li></ul><ul><li>smart pointers </li></ul><ul><li>threads </li></ul><ul><li>Time utilities </li></ul><ul><li>tuple </li></ul><ul><li>unique_ptr </li></ul><ul><li>unordered_map </li></ul><ul><li>weak_ptr </li></ul><ul><li>system error </li></ul>
    13. 13. C++0x: Compiler Support <ul><li>These have varied Language and Library Support </li></ul><ul><ul><li>Gnu C++ (GCC 4.5) </li></ul></ul><ul><ul><li>Microsoft Visual C++ (VC10 Beta 2) </li></ul></ul><ul><ul><li>Sun C++ </li></ul></ul><ul><ul><li>Intel C++ </li></ul></ul><ul><ul><li>IBM XL C++ </li></ul></ul><ul><li>Good Library Support exists in </li></ul><ul><ul><li>Boost </li></ul></ul>
    14. 14. Select Language Features
    15. 15. __cplusplus
    16. 16. __cplusplus <ul><li>In C++98 </li></ul><ul><li>In C++0x, it will be defined as a different (greater) value </li></ul>#define __cplusplus 199711L
    17. 17. long long – a longer integer (C99)
    18. 18. long long: a longer integer <ul><li>An integer that's at least 64 bits long. </li></ul><ul><li>There are no long long long s </li></ul><ul><li>long cannot be spelled short long long . </li></ul><ul><li>long long is in C99 </li></ul>long long x = 9223372036854775807LL;
    19. 19. Right angle brackets
    20. 20. right angle brackets <ul><li>Consider: </li></ul><ul><li>In C++98 this is a syntax error because there is no space between the two >s. </li></ul><ul><li>C++0x recognizes such > as a correct termination of two template argument lists. </li></ul>list<vector<string>> lvs;
    21. 21. static_assert
    22. 22. static_assert: static (compile-time) assertions <ul><li>A static (compile time) assertion consists of a constant expression and a string literal: </li></ul><ul><li>The compiler evaluates the expression and writes the string as an error message if the expression is false (assertion failed). </li></ul>static_assert(expression,string); static_assert(sizeof(long) >= 8, &quot;64-bit support required for this library.&quot;); struct S { X m1; Y m2; }; static_assert(sizeof(S)==sizeof(X)+sizeof(Y), &quot;unexpected padding in S&quot;);
    23. 23. static_assert: static (compile-time) assertions <ul><li>Cannot work for runtime checks: </li></ul><ul><li>Need to throw exception </li></ul>int f(int* p, int n) { static_assert(p==0,&quot;p is not null&quot;); // error: static_assert() expression // not a constant expression // ... }
    24. 24. auto – Type Inference
    25. 25. auto – Type Inference <ul><li>auto deduces the type of a variable from its initializer expression. </li></ul><ul><li>auto keyword can occur as a simple type specifier (useable with cv-qualifiers, *, &) </li></ul><ul><li>The old meaning of auto (&quot;this is a local variable&quot;) is redundant and unused </li></ul><ul><li>Semantics of auto should follow exactly the rules of template argument deduction. </li></ul>auto x = 3.14; // x has type double
    26. 26. auto: Examples int foo(); auto x1 = foo(); // x1 : int const auto & x2 = foo(); // x2 : const int& auto & x3 = foo(); // x3 : int&: // error, cannot bind a // reference to a temporary float & bar(); auto y1 = bar(); // y1 : float const auto & y2 = bar(); // y2 : const float& auto & y3 = bar(); // y3 : float& A* fii() auto * z1 = fii(); // z1 : A* auto z2 = fii(); // z2 : A* auto * z3 = bar(); // error, bar does not // return a pointer type
    27. 27. auto – Use <ul><li>Where type of initializer is not clear up-front </li></ul><ul><ul><li>Inside template functions </li></ul></ul><ul><li>When the type is a lot of typing </li></ul><ul><ul><li>Nested template types </li></ul></ul>
    28. 28. auto: Use <ul><li>In C++98 </li></ul><ul><li>In C++0x </li></ul>template<class T> void printall(const vector<T>& v) { for (auto p = v.begin(); p!=v.end(); ++p) cout << *p << &quot; &quot;; } template<class T> void printall(const vector<T>& v) { for (typename vector<T>::const_iterator p = v.begin(); p!=v.end(); ++p) cout << *p << &quot; &quot;; }
    29. 29. auto: Aliasing <ul><li>Is unintentional aliasing or slicing of objects likely? </li></ul><ul><li>Basing auto on template argument deduction rules provides a natural way for a programmer to express his intention. </li></ul>class B { ... virtual void f(); } class D : public B { ... void f(); } B* d = new D(); ... auto b = *d; // is this casting a reference to a base // or slicing an object? b.f(); // is polymorphic behavior preserved?
    30. 30. auto: Value & Reference Semantics <ul><li>Controlling copying and referencing is the same as with variables whose types are declared explicitly </li></ul><ul><li>Value semantics is the default, and reference semantics is provided through consistent use of &. </li></ul>A foo(); A& bar(); ... A x1 = foo(); // x1 : A auto x1 = foo(); // x1 : A A& x2 = foo(); // error, we cannot bind a non−lvalue // to a non−const reference auto & x2 = foo(); // error A y1 = bar(); // y1 : A auto y1 = bar(); // y1 : A A& y2 = bar(); // y2 : A& auto & y2 = bar(); // y2 : A&
    31. 31. auto: Return Type of Function <ul><li>The return type would be deduced as the type ret in the expression </li></ul>auto add(auto x, auto y) { return x + y; } auto ret = x + y;
    32. 32. auto: Multi-Variable Declarations <ul><li>More than one variable can be declared in a single statement: </li></ul><ul><li>In the case of two or more variables, all deductions must lead to the same type </li></ul><ul><li>Declarations are handled from left to right </li></ul>int i; auto a = 1, *b = &i; auto x = 1, *y = &x;
    33. 33. auto: Direct Initialization <ul><li>The following are allowed: </li></ul>auto x = 1; // x : int auto x(1); // x : int const auto & y(x)  const auto & y = x; new auto (1); // int* auto * x = new auto (1); // int*
    34. 34. decltype
    35. 35. decltype: the type of an expression <ul><li>decltype(E) is the type (&quot;declared type&quot;) of the name or expression E and can be used in declarations. </li></ul>int i; const int&& foo(); struct A { double x; } const A* a = new A(); decltype(i); // type is int decltype(foo()); // type is const int&& decltype(a->x); // type is double
    36. 36. decltype <ul><li>typeof (declared type) has been popular in generic programming. </li></ul><ul><li>typeof implementations in actual use are incomplete and incompatible </li></ul><ul><li>Standard is opting for decltype . </li></ul><ul><li>decltype is really needed for something that is not a variable, such as a return type. </li></ul><ul><li>For the type for a variable about to be initialized auto is often a simpler choice. </li></ul>
    37. 37. decltype: Examples <ul><li>void f(const vector<int>& a, vector<float>& b) { </li></ul><ul><ul><li>typedef decltype(a[0]*b[0]) Tmp; </li></ul></ul><ul><ul><li>for (int i=0; i<b.size(); ++i) { </li></ul></ul><ul><ul><li>Tmp* p = new Tmp(a[i]*b[i]); // ... </li></ul></ul><ul><ul><li>} // ... </li></ul></ul><ul><li>} </li></ul>#include <functional> template<class T, class U> auto mul(T x, U y) -> decltype( x*y ) { return x*y; }
    38. 38. decltype: Semantics <ul><li>decltype(e) is the declared type of the variable or formal parameter for e in </li></ul><ul><ul><li>namespace or local scope, </li></ul></ul><ul><ul><li>a static member variable, </li></ul></ul><ul><ul><li>a literal or </li></ul></ul><ul><ul><li>a formal parameter of a function. </li></ul></ul><ul><li>decltype(e) is a reference type only if the variable or formal parameter is declared as a reference type. </li></ul><ul><li>decltype(e) is the declared return type of the function for the invocation of a function or operator. </li></ul><ul><li>decltype does not evaluate its argument expression. </li></ul><ul><li>decltype(T) is equal to T for any type expression T . </li></ul>
    39. 39. Suffix Return Type Syntax
    40. 40. Suffix Return Type Syntax <ul><li>Use decltype to specify return types that depend on the types of function arguments </li></ul><ul><li>Argument names are not in scope! </li></ul><ul><li>Use hack – works for all types </li></ul><ul><li>New syntax solves  </li></ul>template <class T, class U> decltype( (*(T*)0) + (*(U*)0) ) add(T t, U u); template <class T, class U> decltype( t+u ) add(T t, U u); template <class T, class U> auto add(T t, U u) − > decltype(t + u) ; auto add(auto x, auto y) { return x + y; } // short-cut
    41. 41. Defaulted or Deleted Functions
    42. 42. defaulted or deleted functions <ul><li>Common idiom for Prohibit Copy: </li></ul><ul><li>Idiom to Prohibit Copy is now expressed directly: </li></ul>class X { // ... private: X& operator=(const X&); // No definition X(const X&); }; class X { // ... X& operator=(const X&) = delete; // No copying X(const X&) = delete; };
    43. 43. defaulted or deleted functions <ul><li>When we want the default, we say: </li></ul><ul><li>Being explicit about the default is obviously redundant, but certainly more expressive. </li></ul><ul><li>The &quot;default&quot; mechanism can be used for any function that has a default. </li></ul>class Y { // ... Y& operator=(const Y&) = default; // default // copy semantics Y(const Y&) = default; }
    44. 44. defaulted or deleted functions <ul><li>The &quot;delete&quot; mechanism can be used for any function. For example, to eliminate an undesired conversion: </li></ul>struct Z { // ... Z(long long); // can initialize with // an long long Z(long) = delete; // but not anything less };
    45. 45. enum class
    46. 46. enum: C++98 <ul><li>C++ enum s have 3 Problems: </li></ul><ul><ul><li>Implicitly convert to int </li></ul></ul><ul><ul><ul><li>Cause errors when integer is not desired. </li></ul></ul></ul><ul><ul><li>Export the enumerators to the outer scope </li></ul></ul><ul><ul><ul><li>Cause name clashes. </li></ul></ul></ul><ul><ul><li>Underlying type cannot be specified </li></ul></ul><ul><ul><ul><li>Cause confusion </li></ul></ul></ul><ul><ul><ul><li>Compatibility problems, and </li></ul></ul></ul><ul><ul><ul><li>Makes forward declaration impossible. </li></ul></ul></ul>
    47. 47. enum class: scoped & strongly typed enum <ul><li>enum class es (&quot;strong enums&quot;) </li></ul><ul><ul><li>Are strongly typed and scoped. </li></ul></ul><ul><ul><li>Address problems of conventional enums </li></ul></ul>// traditional enum enum Alert { green, yellow, election, red }; // scoped and strongly typed enum // no export of enumerator names to enclosing scope // no implicit conversion to int enum class Color { red, blue }; enum class TrafficLight { red, yellow, green };
    48. 48. enum class: Scoped Examples <ul><li>Traditional enum s work as usual, but one can now optionally qualify with the enum name. </li></ul>Alert a = 7; // error (as ever in C++) Color c = 7; // error: no int->Color conversion int a2 = red; // ok: Alert->int conversion int a3 = Alert::red; // error in C++98; // ok in C++0x int a4 = blue; // error: blue not in scope int a5 = Color::blue; // error: not Color->int // conversion Color a6 = Color::blue; // ok
    49. 49. enum class: Underlying Type <ul><li>Specify the underlying type </li></ul><ul><ul><li>Simpler interoperability and </li></ul></ul><ul><ul><li>Guaranteed sizes. </li></ul></ul><ul><li>The underlying type must be </li></ul><ul><ul><li>One of the signed or unsigned integer types </li></ul></ul><ul><ul><li>The default is int . </li></ul></ul>
    50. 50. enum class: Underlying Type <ul><li>Examples: </li></ul>// compact representation enum class Color : char { red, blue }; // by default, the underlying type is int enum class TrafficLight { red, yellow, green }; // how big is an E? (&quot;implementation defined&quot;) enum E { E1 = 1, E2 = 2, Ebig = 0xFFFFFFF0U }; // now we can be specific enum EE : unsigned long { EE1 = 1, EE2 = 2, EEbig = 0xFFFFFFF0U };
    51. 51. enum class: Forward Declaration // (forward) declaration enum class Color_code : char; // use of forward declaration void foobar(Color_code* p); // ... // definition enum class Color_code : char { red, yellow, green, blue };
    52. 52. enum class: Use in Standard Library <ul><li>For mapping systems specific error codes: </li></ul><ul><ul><li>enum class errc; </li></ul></ul><ul><li>For pointer safety indicators: </li></ul><ul><ul><li>enum class pointer_safety { </li></ul></ul><ul><ul><ul><ul><li>relaxed, </li></ul></ul></ul></ul><ul><ul><ul><ul><li>preferred, </li></ul></ul></ul></ul><ul><ul><ul><ul><li>strict }; </li></ul></ul></ul></ul><ul><li>For I/O stream errors: </li></ul><ul><ul><li>enum class io_errc { stream = 1 }; </li></ul></ul><ul><li>For asynchronous communications error handling: </li></ul><ul><ul><li>enum class future_errc { </li></ul></ul><ul><ul><ul><ul><li>broken_promise, </li></ul></ul></ul></ul><ul><ul><ul><ul><li>future_already_retrieved, </li></ul></ul></ul></ul><ul><ul><ul><ul><li>promise_already_satisfied }; </li></ul></ul></ul></ul><ul><li>Several of these have operators, such as == defined. </li></ul>
    53. 53. Constant Expression
    54. 54. constexpr: generalized and guaranteed constant expression <ul><li>The constexpr mechanism </li></ul><ul><ul><li>provides more general constant expressions </li></ul></ul><ul><ul><li>allows constant expressions involving user-defined types </li></ul></ul><ul><ul><li>provides a way to guarantee that an initialization is done at compile time </li></ul></ul>
    55. 55. constexpr <ul><li>Function must be of a simple form </li></ul><ul><ul><li>Evaluated at compile time if given constant expressions arguments. </li></ul></ul>enum Flags { good=0, fail=1, bad=2, eof=4 }; constexpr int operator|(Flags f1, Flags f2) { return Flags(int(f1)|int(f2)); } void f(Flags x) { switch (x) { case bad: /* ... */ break; case eof: /* ... */ break; case bad|eof : /* ... */ break; default: /* ... */ break; } }
    56. 56. constexpr <ul><li>constexpr in front of a variable definition </li></ul><ul><ul><li>requires expression to be evaluated at compile time and </li></ul></ul><ul><ul><li>implies const </li></ul></ul>constexpr int x1 = bad|eof; // ok void f(Flags f3) { constexpr int x2 = bad|f3; // error: // can't evaluate // at compile time int x3 = bad|f3; // ok }
    57. 57. constexpr <ul><li>Compile-time evaluation guarantee allow global objects to be placed in read-only storage. </li></ul><ul><li>Works for objects with constructors simple enough to be constexpr and expressions involving such objects: </li></ul>struct Point { int x,y; constexpr Point(int xx, int yy): x(xx), y(yy) { } }; constexpr Point origo(0,0); constexpr int z = origo.x; constexpr Point a[] = {Point(0,0), Point(1,1), Point(2,2)}; constexpr x = a[1].x; // x becomes 1
    58. 58. Initializer List
    59. 59. Initializer List <ul><li>Mechanism for accepting a {} -list is a constructor with an argument of type std::initializer_list<T> . </li></ul>vector<double> v = { 1, 2, 3.456, 99.99 }; list<pair<string,string>> languages = { {&quot;Nygaard&quot;, &quot;Simula&quot;}, {&quot;Richards&quot;, &quot;BCPL&quot;}, {&quot;Ritchie&quot;, &quot;C&quot;} }; map<vector<string>,vector<int>> years = { { {&quot;Maurice&quot;, &quot;Vincent&quot;, &quot;Wilkes&quot;}, {1913, 1945, 1951, 1967, 2000} }, { {&quot;Martin&quot;, &quot;Richards&quot;}, {1982, 2003, 2007} }, { {&quot;David&quot;, &quot;John&quot;, &quot;Wheeler&quot;}, {1927, 1947, 1951, 2004} } };
    60. 60. Initializer List <ul><li>The initializer list can be of arbitrary length, but must be homogeneous (all elements must be of a the template argument type, T , or convertible to T ). </li></ul>void f(initializer_list<int>); f({1,2}); f({23,345,4567,56789}); f({}); // the empty list f{1,2}; // error: function call ( ) missing years.insert({ {&quot;Bjarne&quot;,&quot;Stroustrup&quot;}, {1950, 1975, 1985}});
    61. 61. Initializer List <ul><li>A container may implement an initializer-list constructor like this: </li></ul><ul><li>template<class E> </li></ul><ul><li>class vector { </li></ul><ul><li>public: </li></ul><ul><li>vector (std::initializer_list<E> s) </li></ul><ul><ul><ul><ul><li>// initializer-list constructor { </li></ul></ul></ul></ul><ul><ul><ul><ul><li>reserve(s.size()); // get the right </li></ul></ul></ul></ul><ul><ul><ul><ul><li>// amount of space </li></ul></ul></ul></ul><ul><ul><ul><ul><li>uninitialized_copy(s.begin(), s.end(), </li></ul></ul></ul></ul><ul><ul><ul><ul><li>elem); // initialize elements </li></ul></ul></ul></ul><ul><ul><ul><ul><li>// (in elem[0:s.size())) </li></ul></ul></ul></ul><ul><ul><ul><ul><li>sz = s.size(); // set vector size </li></ul></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><li>// ... as before ... </li></ul><ul><li>}; </li></ul>
    62. 62. Initializer List <ul><li>std::vector has an explicit constructor from int and an initializer-list constructor: </li></ul>vector<double> v1(7); // ok: v1 has 7 elements v1 = 9; // error: no int  vector vector<double> v2 = 9; // error: no int  vector void f(const vector<double>&); f(9); // error: no int  vector vector<double> v1{7}; // ok: v1 has 1 element (7) v1 = {9}; // ok: v1 now has 1 element (9) vector<double> v2 = {9}; // ok: v2 has 1 element (9) f({9}); // ok: f is called with { 9 }
    63. 63. Initializer List <ul><li>std::vector … </li></ul><ul><li>vector<vector<double>> vs = { </li></ul><ul><ul><li>vector<double>(10), // ok: explicit construction </li></ul></ul><ul><ul><li>// (10 elements) </li></ul></ul><ul><ul><li>vector<double>{10}, // ok explicit construction </li></ul></ul><ul><ul><li>// (1 element, 10) </li></ul></ul><ul><ul><li>10 // error: vector's constructor </li></ul></ul><ul><ul><li>// is explicit </li></ul></ul><ul><li>}; </li></ul>
    64. 64. Initializer List <ul><li>A function can access the initializer_list as an immutable sequence. </li></ul><ul><li>A constructor that takes a single argument of type std::initializer_list is called an initializer-list constructor. </li></ul><ul><li>The standard library containers, string, and regex have initializer-list constructors </li></ul><ul><li>Initializer-list can be used as a Range . </li></ul>void f(initializer_list<int> args) { for (auto p=args.begin(); p!=args.end(); ++p) cout << *p << &quot; &quot;; }
    65. 65. In–Class Member Initialization
    66. 66. In-class Member Initializations <ul><li>In C++98, only static const members of integral types can be initialized in-class, and the initializer has to be a constant expression </li></ul><ul><li>int var = 7; </li></ul><ul><li>class X { </li></ul><ul><ul><li>static const int m1 = 7; // ok </li></ul></ul><ul><ul><li>const int m2 = 7; // error: not static </li></ul></ul><ul><ul><li>static int m3 = 7; // error: not const </li></ul></ul><ul><ul><li>static const int m4 = var; // error: initializer not </li></ul></ul><ul><ul><li>// constant expression </li></ul></ul><ul><ul><li>static const string m5 = </li></ul></ul><ul><ul><li>&quot;odd&quot;; // error: not integral </li></ul></ul><ul><ul><li>// type </li></ul></ul><ul><ul><li>// ... </li></ul></ul><ul><li>}; </li></ul>
    67. 67. In-class Member Initializations <ul><li>In C++0x, allow: </li></ul><ul><li>To mean: </li></ul><ul><li>class A { </li></ul><ul><li>public: </li></ul><ul><ul><li>int a = 7 ; </li></ul></ul><ul><li>}; </li></ul><ul><li>class A { </li></ul><ul><li>public: </li></ul><ul><ul><li>int a; </li></ul></ul><ul><ul><li>A() : a(7) {} </li></ul></ul><ul><li>}; </li></ul>
    68. 68. In-class Member Initializations <ul><li>For multiple Constructors: </li></ul><ul><li>To mean: </li></ul><ul><li>class A { </li></ul><ul><li>public: </li></ul><ul><ul><li>A(): a(7), b(5), </li></ul></ul><ul><ul><li>hash_algorithm(&quot;MD5&quot;), s(&quot;Constructor run&quot;) {} </li></ul></ul><ul><ul><li>A(int a_val) : a(a_val), b(5), </li></ul></ul><ul><ul><li>hash_algorithm(&quot;MD5&quot;), s(&quot;Constructor run&quot;) {} </li></ul></ul><ul><ul><li>A(D d) : a(7), b(g(d)), </li></ul></ul><ul><ul><li>hash_algorithm(&quot;MD5&quot;), s(&quot;Constructor run&quot;) {} </li></ul></ul><ul><ul><li>int a, b; </li></ul></ul><ul><li>private: </li></ul><ul><ul><li>HashingFunction hash_algorithm; // Hash </li></ul></ul><ul><ul><li>std::string s; // State </li></ul></ul><ul><li>}; </li></ul>
    69. 69. In-class Member Initializations <ul><li>Simplify: </li></ul><ul><li>To mean: </li></ul><ul><li>class A { </li></ul><ul><li>public: </li></ul><ul><ul><li>A(){} </li></ul></ul><ul><ul><li>A(int a_val) : a(a_val) {} </li></ul></ul><ul><ul><li>A(D d) : b(g(d)) {} </li></ul></ul><ul><ul><li>int a = 7, b = 5; </li></ul></ul><ul><li>private: </li></ul><ul><ul><li>HashingFunction hash_algorithm{&quot;MD5“}; // Hash </li></ul></ul><ul><ul><li>std::string s{&quot;Constructor run“}; // State </li></ul></ul><ul><li>}; </li></ul>
    70. 70. Uniform Initialization
    71. 71. Uniform Initialization Syntax & Semantics <ul><li>C++98 offers context-dependent ways for initializing an object </li></ul>string a[] = {&quot;foo&quot;, &quot;bar&quot;}; // ok: initialize array vector<string> v = {&quot;foo&quot;, &quot;bar&quot;}; // error: initializer list // for non-aggregate vector void f(string a[]); f( { &quot;foo&quot;, &quot; bar&quot; } ); // syntax error: block as argument int a = 2; // &quot;assignment style&quot; int[] aa = { 2, 3 }; // assignment style with list complex z(1,2); // &quot;functional style&quot; initialization x = Ptr(y); // &quot;functional style&quot; for // conversion/cast/construction int a(1); // variable definition int b(); // function declaration int b(foo); // variable definition or // function declaration
    72. 72. Uniform Initialization Syntax & Semantics <ul><li>C++0x allow {} -initializer lists for all initializations </li></ul>X x1 = X{1,2}; X x2 = {1,2}; // the = is optional X x3{1,2}; X* p = new X{1,2}; struct D : X { D(int x, int y) :X{x,y} { /* ... */ }; }; struct S { int a[3]; S(int x, int y, int z) :a{x,y,z} { /* ... */ }; // solution to old problem };
    73. 73. Uniform Initialization Syntax & Semantics <ul><li>X{a} constructs the same value in every context (where legal) </li></ul>X x{a}; X* p = new X{a}; z = X{a}; // use as cast f({a}); // function argument (of type X) return {a}; // function return value // (function returning X)
    74. 74. Prevent Narrowing
    75. 75. Preventing Narrowing <ul><li>C++98 implicitly truncates. </li></ul><ul><li>In C++0x, {} initialization doesn't narrow: </li></ul>int x = 7.3; // Ouch! void f(int); f(7.3); // Ouch! int x1 = {7.3}; // error: narrowing double d = 7; int x2{d}; // error: narrowing (double to int) // ok: even though 7 is an int, this is not narrowing char x3{7}; // error: double to int narrowing vector<int> vi = { 1, 2.3, 4, 5.6 };
    76. 76. for Range
    77. 77. Range for statement <ul><li>Iterates through a &quot;range&quot; </li></ul><ul><ul><li>STL-sequence defined by a begin() and end(). </li></ul></ul><ul><ul><li>All standard containers </li></ul></ul><ul><ul><li>std::string, </li></ul></ul><ul><ul><li>an initializer list, </li></ul></ul><ul><ul><li>an array, and </li></ul></ul><ul><ul><li>anything (like istream) for which begin() and end() are defined </li></ul></ul>
    78. 78. Range for statement: Examples <ul><li>The begin() (and end() ) can be a member to be called x.begin() or a free-standing function to be called begin(x) . </li></ul>void f(const vector<double>& v) { for ( auto x : v ) cout << x << ' '; for ( auto& x : v ) ++x; // use a reference to // change the value } for ( const auto x : { 1,2,3,5,8,13,21,34 } ) cout << x << ' ';
    79. 79. Delegating Constructor
    80. 80. Delegating Constructors <ul><li>In C++98, two constructors do the same thing with repeat or call of &quot;init() function.&quot; </li></ul>class X { int a; validate(int x) { if (0<x && x<=max) a=x; else throw bad_X(x); } public: X(int x) { validate(x); } X() { validate(42); } X(string s) { int x = lexical_cast<int>(s); validate(x); } // ... };
    81. 81. Delegating Constructors <ul><li>In C++0x, define one constructor in terms of another: </li></ul>class X { int a; public: X(int x) { if (0<x && x<=max) a=x; else throw bad_X(x); } X() : X{42} { } X(string s) : X{lexical_cast<int>(s)} { } // ... };
    82. 82. Inherited Constructor
    83. 83. Inherited Constructors <ul><li>In C++98, we can &quot;lift&quot; a set of overloaded functions from a base class to derived class: </li></ul><ul><li>Lifting does not work for Constructors </li></ul>struct B { void f(double); }; struct D : B { void f(int); }; B b; b.f(4.5); // fine D d; d.f(4.5); // calls D::f(int) with argument 4! struct B { void f(double); }; struct D : B { using B::f; // bring all f()s from B into scope void f(int); // add a new f() }; B b; b.f(4.5); // fine D d; d.f(4.5); // fine: calls D::f(double) // which is B::f(double)
    84. 84. Inherited Constructors <ul><li>class Base { </li></ul><ul><ul><li>Base(int); </li></ul></ul><ul><li>}; </li></ul><ul><li>class Derived : public Base { </li></ul><ul><li>public: </li></ul><ul><ul><li>using Base::f; // lift Base's f to Derived's scope </li></ul></ul><ul><ul><li>// -- works in C++98 </li></ul></ul><ul><ul><li>void f(char); // provide a new f </li></ul></ul><ul><ul><li>void f(int); // prefer this f to Base::f(int) </li></ul></ul><ul><ul><li>using Base::Base;// lift Base’s constr’s to Derived's </li></ul></ul><ul><ul><li>// scope -- C++0x only </li></ul></ul><ul><ul><li>Derived(char); // provide a new constructor </li></ul></ul><ul><ul><li>Derived(int); // prefer this constructor to </li></ul></ul><ul><ul><li>// Base::Base(int) </li></ul></ul><ul><ul><li>// ... </li></ul></ul><ul><li>}; </li></ul>
    85. 85. Inherited Constructors: Initialization Slip <ul><li>Use Member Intializer </li></ul><ul><li>struct B1 { B1(int) { } }; </li></ul><ul><li>struct D1 : B1 { </li></ul><ul><ul><li>using B1::B1; // implicitly declares D1(int) </li></ul></ul><ul><ul><li>int x; </li></ul></ul><ul><li>}; </li></ul><ul><li>void test() { </li></ul><ul><ul><li>D1 d(6); // Oops: d.x is not initialized </li></ul></ul><ul><ul><li>D1 e; // error: No default constructor </li></ul></ul><ul><li>} </li></ul><ul><li>struct B1 { B1(int) { } }; </li></ul><ul><li>struct D1 : B1 { </li></ul><ul><ul><li>using B1::B1; // implicitly declares D1(int) </li></ul></ul><ul><ul><li>int x{0}; // x is initialized </li></ul></ul><ul><li>}; </li></ul><ul><li>void test() { D1 d(6); // d.x is 0 </li></ul><ul><li>} </li></ul>
    86. 86. nullptr
    87. 87. nullptr: A null pointer literal <ul><li>nullptr </li></ul><ul><ul><li>is a reserved word. </li></ul></ul><ul><ul><li>is a literal, just like 1 and true. </li></ul></ul><ul><ul><li>address of nullptr itself can-not be taken (No memory) </li></ul></ul><ul><ul><li>designates a constant rvalue of type decltype(nullptr) or nullptr_t. </li></ul></ul><ul><ul><ul><li>typedef decltype(nullptr) nullptr_t; </li></ul></ul></ul><ul><li>nullptr_t </li></ul><ul><ul><li>is not a reserved word. It is defined in <cstddef>. </li></ul></ul><ul><ul><li>is a POD type </li></ul></ul><ul><ul><li>is convertible to both a pointer type and a pointer-to-member type. </li></ul></ul><ul><ul><li>has equivalent objects with identical behavior that </li></ul></ul><ul><ul><ul><li>may differ in cv-qualification </li></ul></ul></ul><ul><ul><ul><li>may differ in being rvalues or lvalues </li></ul></ul></ul><ul><ul><ul><li>may be be copied and thrown. </li></ul></ul></ul>
    88. 88. nullptr: Example char* p = nullptr; int* q = nullptr; char* p2 = 0; // 0 still works and p==p2 void f(int); void f(char*); f(0); // call f(int) f(nullptr); // call f(char*) void g(int); g(nullptr); // error: nullptr is not an int int i = nullptr; // error nullptr is not an int if(n2 == 0); // evaluates to true if(n2 == nullptr); // error if(nullptr); // error, no conversion to bool if(nullptr == 0); // error
    89. 89. Rvalue references
    90. 90. Rvalue references <ul><li>Lvalue: used on the left-hand side of an assignment </li></ul><ul><li>Rvalue: Used on the right-hand side of an assignment </li></ul><ul><li>Christopher Strachey </li></ul><ul><ul><li>Introduced Lvalue / Rvalue notions </li></ul></ul><ul><ul><li>Father of C++'s distant ancestor CPL and </li></ul></ul><ul><ul><li>Denotational Semantics </li></ul></ul><ul><li>In C++98, allowed reference bindings are: </li></ul><ul><ul><li>Non-const references can bind to Lvalue, </li></ul></ul><ul><ul><li>Const references can bind to Lvalue </li></ul></ul><ul><ul><li>Const references can bind to Rvalue </li></ul></ul><ul><li>In C++98, disallowed reference bindings are: </li></ul><ul><ul><li>No reference can bind to a Non-const Rvalue. </li></ul></ul><ul><ul><li>Protects against uses of temporaries after their destruction </li></ul></ul>
    91. 91. Rvalue reference <ul><li>If that incr(0) were allowed </li></ul><ul><ul><li>Some temporary that nobody ever saw would be incremented or </li></ul></ul><ul><ul><li>The value of 0 would become 1. </li></ul></ul>void incr( int& a ) { ++a; } int i = 0; incr(i); // i becomes 1 incr(0); // error: 0 in not an lvalue
    92. 92. Rvalue reference <ul><li>Consider: </li></ul><ul><li>swap would be expensive if T is a type (like string and vector) </li></ul><ul><li>Standard Library, use specializations of string and vector swap() </li></ul><ul><li>Interestingly: We didn't want any copies at all. We just wanted to move the values of a , b , and tmp . </li></ul><ul><li>template<class T> swap(T& a, T& b) // “typical swap&quot; </li></ul><ul><li>{ </li></ul><ul><ul><li>T tmp(a);// now we have two copies of a </li></ul></ul><ul><ul><li>a = b; // now we have two copies of b </li></ul></ul><ul><ul><li>b = tmp; // now we have two copies of tmp (aka a) </li></ul></ul><ul><li>} </li></ul>
    93. 93. Rvalue reference: move semantics <ul><li>Move Constructor & Move Assignment: </li></ul><ul><li>template<class T> class vector { </li></ul><ul><ul><li>// ... </li></ul></ul><ul><ul><li>vector(const vector&); // copy constructor </li></ul></ul><ul><ul><li>vector(vector&&); // move constructor </li></ul></ul><ul><ul><li>vector& operator=(const vector&); // copy assignment </li></ul></ul><ul><ul><li>vector& operator=(vector&&); // move assignment </li></ul></ul><ul><li>}; </li></ul><ul><li>// move constructor and move assignment takes non-const && </li></ul><ul><li>// they can, and usually do, write to their argument </li></ul>
    94. 94. Copy vs Move Semantics <ul><li>C and C++ are built on copy semantics. </li></ul><ul><ul><li>Move semantics augments copy semantics. </li></ul></ul><ul><li>A general user defined class might be </li></ul><ul><ul><li>both copyable and movable, </li></ul></ul><ul><ul><li>one or the other, or </li></ul></ul><ul><ul><li>neither. </li></ul></ul><ul><li>A copy leaves the source unchanged </li></ul><ul><li>A move leaves the source in a consistent state </li></ul><ul><li>Choose move to allow any state of the source </li></ul><ul><li>For PODs, move and copy are identical operations </li></ul><ul><ul><li>MOV R1, R2 // Means copy R2 to R1 </li></ul></ul>
    95. 95. Rvalue reference: move semantics <ul><li>The && indicates an &quot;rvalue reference&quot;. </li></ul><ul><li>An rvalue reference can bind to an rvalue (but not to an lvalue) </li></ul>X a; X f(); X& r1 = a; // bind r1 to a (an lvalue) X& r2 = f(); // error: f() is an rvalue; // can't bind X&& rr1 = f(); // fine: bind rr1 to temporary X&& rr2 = a; // error: bind a is an lvalue
    96. 96. Rvalue reference: move semantics <ul><li>Move assignment is more effective for objects with resources. For strings s1=s2 </li></ul><ul><ul><li>Copy Assignment </li></ul></ul><ul><ul><ul><li>makes a copy of s2 's chars </li></ul></ul></ul><ul><ul><li>Move Assignment </li></ul></ul><ul><ul><ul><li>lets s1 treat s2 's chars as its own </li></ul></ul></ul><ul><ul><ul><li>deletes s1 's old characters or </li></ul></ul></ul><ul><ul><ul><li>leaves them in s2 , presumably to be destroyed </li></ul></ul></ul><ul><li>How do we know whether it's ok to simply move from a source? We tell the compiler: </li></ul>
    97. 97. Rvalue reference: move semantics <ul><li>move(x) : “You can treat x as an rvalue&quot;. </li></ul><ul><li>template<class T> </li></ul><ul><li>void swap(T& a, T& b) // &quot;perfect swap&quot; (almost) </li></ul><ul><li>{ </li></ul><ul><ul><li>T tmp = move(a); // could invalidate a </li></ul></ul><ul><ul><li>a = move(b); // could invalidate b </li></ul></ul><ul><ul><li>b = move(tmp); // could invalidate tmp </li></ul></ul><ul><li>} </li></ul>
    98. 98. Standard Library
    99. 99. References <ul><li>ISO/IEC JTC1/SC22/WG21 - The C++ Standards Committee. </li></ul><ul><li>C++0x FAQ: by Bjarne Stroustrup. </li></ul><ul><li>C++0x Support in GCC: </li></ul><ul><li>C++0x Support in Visual C++: Visual Studio 2010 Beta 2. (19-Oct-09) </li></ul><ul><li>C++0x. </li></ul><ul><li>C++0x: The Dawning of a New Standard: (Aug-09) - Overview: C++ Gets an Overhaul, Easier C++: An Introduction to Concepts, Simpler Multithreading in C++0x, The State of the Language: An Interview with Bjarne Stroustrup & Timeline: C++ in Retrospect: </li></ul><ul><li>C++0x - An Overview. </li></ul>
    100. 100. Credit <ul><li>Santanu Sinha </li></ul><ul><ul><li>Trying out examples in GCC </li></ul></ul>
    101. 101. Thank You