# Presentation: 085823

## C++: New and Improved!

- Last update: 2008-03-11

## C++ :  New and Improved!

- Walter E. Brown, Ph.D.  <wb@fnal>
*Computing Division*
- f *Fermi National Accelerator Laboratory*
- 2008-03-12
- Copyright © 2007-2008 by Walter E. Brown.  All rights reserved.

## A little about me

- B.A. (math’s); M.S., Ph.D. (computer science).
- Professional programmer for nearly 40 years.
- Experienced in both academia and industry:
- Founded Comp.Sci. Dept.; served as Professor and Dept. Head; taught/mentored at all levels.
- Managed/mentored programming staff for a computer reseller; self-employed as a software consultant and commercial trainer.
- At Fermilab since 1996; now in Computing Division/LSC Dept.,specializing in C++ consulting and programming.
- Participant in the international C++ standardization process.
- Be forewarned: Based on the above training and experience, I hold some rather strong opinions about computer software and programming methodology — these opinions are not shared by all programmers, but they should be!  

## What do I mean by “new” and “improved” C++?

- Evolutionary advances via core language and standard library features:
- That extend or generalize C++03 behavior, or ...
- That have no precedent in C++03.
- By design, these new and improved C++0X features:
- Will interact well and compatibly with C++03 features.
- Will supplement/complement C++03 behaviors.
- Will let us create programs that are:
- Even closer to our problem domain (*i.e.*, at higher levels of abstraction), when that’s what we want to do.
- Even closer to our machines’ architecture (*i.e.*, at lower levels of abstraction), when that’s what we want to do.

## WG21’s approach to C++ evolution

- General principles:
- Preserve source compatibility.
- Support novices (*n*novices  *n*experts ).
- Help programmers to write better programs:
- Maintain or increase type safety.
- Keep to the zero-overhead principle.
- Removing a feature is only rarely feasible:
- Stability and compatibility are major concerns.
- It’s very hard to remove a feature without breaking somebody’s code, but:
- Keyword auto is so rarely used that we gave it new semantics.
- While library’s auto_ptr<> is heavily used, it has inherent issues; we’ve deprecated it and provide/promote unique_ptr<> instead.

## Goals

- For the core language:
- Make C++ easier to teach and learn.
- Make the rules more general and more uniform.
- Make C++ better for building libraries; prefer libraries over language extensions.
- For the standard library:
- Improve support for generic programming and other programming paradigms (styles).
- Extend the library into new domains.
- Make use of new core language technologies.

## Features’ status

- All have been proposed and accepted in principle:
- Most are based on existing practice in some compiler/library.
- Quite a few are already in gcc 4.3.0, released this week.
- A few are not yet fully implemented, and we’re a bit nervous.
- Most have already been formally adopted:
- Detailed descriptions are merged into the “Working Draft” ...
- But a few are still under discussion, so could still change.
- Disclaimer:
- Technically, _anything_ could still change.

## Planned timeline

- WG21 expects to finish drafting work by the end of 2008:
- “Working Draft”  “Final Committee Draft”
- Balloting by ISO members (national standards bodies) planned for early/mid 2009.
- Hope to have the new C++ Standard out by late 2009:
- Could encounter technical resistance.
- Could encounter political resistance.
- Could encounter publishing delays.

## Also forthcoming ...

- Some good library ideas/features have been delayed simply for lack of time to work on them:
- Plan to issue these in Technical Report form ...
- After C++0X is voted out of committee.
- Work on some of these TR’s has already been approved:
- Modules (core language).
- Decimal arithmetic (core language and standard library).
- Also approved: work toward a separate standard for a mathematical special functions standard library:
- Initially proposed by Fermilab;
- I have been appointed Project Editor for this standard.

## Final disclaimers

- This survey of features emphasizes breadth over depth:
- Not a tutorial; simplifies or suppresses many details.
- Omits all background discussion (rationale, design issues, ...).
- But identifies papers containing such information
- _[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/)_
- C++0X isn’t designed to “fix” anything:
- It’s aimed at improving the C++ programming experience ...
- By improving/extending the programmer’s standard toolkit.
- “[T]he primary purpose of a programming language is to help the programmer in the practice of his art.”				― C. A. R. Hoare, 1973

- N2461

## New types and corresponding literals

- New long long integral types, signed and unsigned:
- sizeof(long long)  ≥  sizeof(long).
- Corresponding literals, *e.g.*, 42ULL.
- New pointer literal, nullptr, of type nullptr_t:
- A new name for the same null pointer value ...
- To avoid confusion with 0 as an int constant.
- New Unicode character types:
- A char can now hold a UTF-8 character.
- A char16_t, *e.g.*, u'x', holds a UTF-16 character; a char32_t, *e.g.*, U'x', holds a UTF-32 character.
- u8"Hello" is a UTF-8 string literal; u"Hello"	 is a UTF-16 string literal;U"Hello"	 is a UTF-32 string literal.

- N1811

- N2431

- N2249

## New integer type aliases (from C99)

- All found in new library header  <cstdint>:
- Names all have the form  int_t  or  uint_t .
- Required iff some type has the  size/behavior.

| Purpose | Examples |  |
| --- | --- | --- |
| Exact-width | int64_t | uint32_t |
| Minimum-width | int_least64_t | uint_least32_t |
| Fastest minimum-width | int_fast64_t | uint_fast32_t |
| Greatest-width | intmax_t | uintmax_t |

- N1835

## Syntax to improve utility of existing features

- Consecutive closing angle brackets now okay:
- typedef  std::vector<std::vector<int>>  Table;
- New for statement variant iterates over a complete range:
- int  a[ ]  =  {  } ;for ( int &  x  :  a )*  // traverse entire array *a*, 1 element/iteration*    x  *=  2;
- Can now default or delete standard member functions:
- class  C *  // non-copyable*{       C( )	=  default ;    C( C const & )	=  delete ;    C &  operator = ( C const & )	=  delete ;};

- N1757

- N2394

- N2346

## New flexibility in declaration syntax

- New permitted function declaration syntax:
- auto  f ( double )  –>  std:vector<double>;
- Type deduction from initializers via auto:
- std::vector<int>::iterator  it  =  v.begin( ); can now be written  auto  it  =  v.begin( );
- Uses same type deduction rules already used for templates.
- Type queries via decltype (“declared-type-of”):
- typedef  decltype( x * y )  result_t;
- Especially useful in generic programming, when type interactions are often not known to the programmer:
- template< class T, class U >auto  product ( T t, U u )  –>  decltype( t * u )   {  return  t * u;  }

- N2541

- N1984

- N2343

## Feature completion: compile-time assertions

- Known as static_assert( , "" );
- Inspired by/augments run-time assert( ) macro and compile-time #error directive.
- May appear at namespace, block, or class scope.
- Evaluated at compile-time; produces diagnostic if false.
- Takes a predicate and a string literal; emits the literal as a diagnostic if the evaluated predicate is false:
- template< typename T >struct  Check{       static_assert( sizeof( int)  <= sizeof( T )		          , "Check: type not big enough" );};

- N1720

## Feature extension: template aliases

- Extends typedef notion.
- Adopts/extends alias-declaration syntax (used today for only namespace aliases):
- using  *identifier*  =  *type-id *;
- Extended to templates:
- template< class >    struct  A  {  };template< class T >    using  B  =  A<T> ;    *// *B* is now an alias for template *A

- N2258

## Enhancements to constructors

- Delegating c’tors:
- Reduces/avoids duplication among c’tors within a class.
- A c’tor may now “delegate” by invoking another c’tor of the same type to initialize.
- Eliminates need for special initialization member functions; one of the c’tors can serve this purpose.
- After regaining control, the delegating c’tor may optionally perform additional initialization actions as well.
- Inheriting c’tors:
- Derived class c’tors may now be inherited from a base class.
- class  D  :  public  B   {       using  B::B;*  // declare (inherit) *B*’s non-default, non-copy c’tors*};

- N2540

- N1986

## Feature completion: new reference types

- T &&  is notation for new rvalue reference types:
- C++03 *reference* types T &  *lvalue reference* types.
- Allows code to distinguish between a memory cell (lvalue) and its contents (rvalue).
- Enables move semantics (*e.g.*, via std::move( ) ):
- When copying is inappropriate or too expensive, can transfer resource ownership instead.
- class  C   {  *  // movable*    C( C && );	*// move c’tor overload*    C &  operator = ( C && );	*// move assignment overload*};
- Also enables perfect forwarding (*e.g.*, via std::forward( ) ).

- N2118

## Generalization: compile-time constant expressions

- Means of declaring that an expression (not necessarily integral) be evaluated _by_ _the_ _compiler_ whenever possible:
- Can declare constexpr variables and (within limits) functions.
- constexpr  double  sqr( double  x )   {  return  x * x;  }constexpr  double  gamma  =  sqr( 2.5 );
- Evaluated at compile time iff the argument can itself be evaluated at compile time.
- double const  alpha  =  2.5;constexpr  double  gamma  =  sqr( alpha );	 *// okay*
- extern double  beta;constexpr  double  gamma1  =  sqr( beta );	*// error!*double const  gamma2  =  sqr( beta );	*// okay; runtime*

- N2235

## Generalization: uniform initialization syntax

- How can we initialize a variable of type T with a value v?
- T  t1  =  v;*	**// copy-initialization (copy c’tor or equivalent)*T  t2( v );*	**// direct-initialization*T  t3  =  { v };*	**// initialize from C-style initializer list*T  t4  =  T( v );*	**// make a *T* out of *v*, then copy that *T* to *t4
- Today, different definitions of T allow 0, 1, 2, 3, or all 4 of these definitions to compile for identical v!
- Want every C++0X initialization to accept a {  } initializer:
- As an rvalue of new type std::initializer_list< T > ...
- To initialize free, base, member, or newed objects, ...
- As well as function parameters and return expressions.
- This incidentally solves some old problems as well (*e.g.*, initializing a std:vector< > with a sequence of values).

- N2531

## Uniform initialization syntax at work

- T  v  =  { 1, 2, 3.14 } ;	*//  a free automatic variable*T * p  =  new T { 1, 2, 3.14 } ;	*// a dynamically-created variable*
- T &             r1  =  { 1, 2, 3.14 } ;	*//  error: const-incorrect*T const &  r2  =  { 1, 2, 3.14 } ;	*//  const lref* T &&          r3  =  { 1, 2, 3.14 } ;	*//  rref*
- void  f1( T );                f1( { 1, 2, 3.14 } );	*// pass by-value *void  f2( T const & ); f2( { 1, 2, 3.14 } );	*// pass by-const-lref*void  f3( T & );            f3( { 1, 2, 3.14 } );	*// error: pass by-lref*void  f4( T && );         f4( { 1, 2, 3.14 } );	*// pass by-rref*
- T  g( ) { return { 1, 2, 3.14 } ; }	*// return value*
- class D  :  public T  {    T  m;    D( )  :  T { 1, 2, 3.14 } , m { 1, 2, 3.14 }  {  }   *// base, member*};

## New language feature: concepts

- Inspired by standard library’s *requirements tables*:
- Concepts are notionally described as a type system for types.
- Leads to vastly improved diagnostics when an algorithm is instantiated with a type not matching the algorithm’s needs.
- The core language will provide mechanisms to:
- Articulate a set of requirements/constraints for a type, ...
- Impose, _*a priori*_, such requirements on an algorithm, and ...
- Define how a type meets such requirements.
- The standard library will provide:
- A library of standard concepts (mostly replacing today’s extra-linguistic requirements tables), and ...
- Concept-based requirements for each standard algorithm.

- N2520

## Concepts at work

*// Articulate requirements/constraints for a type* T*:*concept  std::Swappable< typename T >{   void  swap( T &, T & );   };
*// Impose requirements on the type used to instantiate this algorithm;**// implement the algorithm using only those requirements*:template< typename  T >void  my_sort( T *  from, T * upto )    requires  std::Swappable<T> {    ;  swap( *p, *q );   ;   }
*// Define how *int* will meet the *Swappable* requirements:*concept_map  std::Swappable< int >{   void  swap( int &  t1, int &  t2 )   {  std::swap( t1, t2 );  }   }
*// Instantiate the algorithm on* int*; okay since *int* is *Swappable*:*my_sort< int >( a + 0, a + n );

## New language feature: concurrency

- Intended to standardize support for:
- Multi-core processors.
- Client-server programming.
- Current POSIX and Windows standards re OS threads and shared memory ...
- But not replace other standards (*e.g.*, MPL, OpenMP, ...).
- Core language adjustments/additions:
- What does it mean to have two threads sharing memory?
- How does this affect variables?
- Standard library additions/clarifications:
- How to create/synchronize/terminate threads?
- How to handle exceptions between threads?

## Concurrency in the core language

- “Loosely-coupled shared memory”:
- Today’s hardware does not support stronger coupling.
- Memory races (multiple threads updating a single memory cell) will evoke undefined behavior.
- Atomic (indivisible) operations will be provided.
- Locks and atomics will be used to coordinate/communicate non-atomic writes between two threads.
- Adjustments to variables:
- Thread-local storage will be provided.
- Will synchronize initialization of function-local statics.
- Will restrict certain dynamic initialization of non-local variables to enable their concurrent initialization.

- N2480

## Concurrency in the standard library

- Thread instantiation via basic thread type:
- Supports basic fork( ) and join( ) operations.
- Supports standard access to OS-specific details.
- Supports thread synchronization:
-  Via variables of type mutex, and ...
-  Via condition variables.
- Thread termination is voluntary:
- Synchronous in all cases, with no interrupts permitted.
- Typical termination is via return from the function called when the thread was initiated.

- N2497

## And there’s still more!

- Variadic template parameters:
- Now possible to define a template taking a variable number of template parameters (a “parameter pack”).
- Useful to implement library facilities, *e.g.*, std::tuple< >.
- Strongly-typed enums (also termed scoped enums):
- enum class E  :  long  { E1, E2, E3 = 100, E4 /* = 101 */ };
- E1, *et al.*, are exclusively in E’s scope (*i.e.*, E::E1).
- Enumerators have an underlying integral representation, whose type the programmer may optionally specify.
- _All_ template parameters may now have defaults:
- template< class T = long double > *  // not allowed in C++03*T  pi ( )  { return 3.1415926535897932384626433L; }

- N2080

- N2347

- Core #226

## Monomorphic lambda expressions and closures

- Anonymous function objects (lambdas):
- Definable at point of use.
- May be local to (nested within) another scope.
- Feature loosely based on Alonzo Church’s λ-calculus [1936].
- Examples:
- std::transform(  v.begin( ), v.end( ), v.begin( ) 		         ,  [ ] ( double x )  { return  x + pi( ); }   );
- auto  add_pi_to  =  [ ] ( double x )  { return  x + pi( ); } ; std::transform(  v.begin( ), v.end( ), v.begin( )		         ,  add_pi_to  );

- N2550

## And yet more language additions, improvements, ...

- Relaxation of POD restrictions; new notion of trivial type.
- New data alignment support: alignof() and alignas().
- Raw string literals.
- Extension to obtain the size of a data member via sizeof.
- Extensible (user-defined) literals.
- Generalized attribute declarations.
- Improvements to union (“Toward a More Perfect Union”).
- Conversion operators now optionally explicit.
- Extended friend declarations.
- C99 preprocessor semantics.

## And I’ve barely mentioned the standard library

- Random number engines/distributions.
- Regular expressions*.*
- Type traits (for template metaprogramming).
- Posix-related enhancements to standard exceptions.
- Generic callable wrapper function< > and binder bind< >.
- Smart pointers: shared_ptr< >, unique_ptr< >.
- Containers: array< >, tuple< >, and forward_list< >.
- Hash tables: unordered_map< >, unordered_set< >, *etc.*
- Concurrency support: atomic< >s, threads, mutexes, *etc.*
- New variadic min( ), max( ), and new minmax( ) algorithms.

## Summary

- Lots and lots of useful improvements are coming in C++0X:
- Missing a few hoped-for items (*e.g.*, garbage collection), ...
- But WG21 is simply running out of time.
- Compilers (*e.g.*, gcc) and libraries (*e.g.*, Boost) already have very many of the new features available:
- We can start now to learn/try out the new features, and ...
- We can start our planning for a transition.
- “C++ is a general purpose programming language for enjoyable programming by serious programmers.”					― Bjarne Stroustrup, 1991

##  C++ :  New and Improved!

- Walter E. Brown, Ph.D.  <wb@fnal>
*Computing Division*
- f *Fermi National Accelerator Laboratory*
- 2008-03-12
- Copyright © 2007-2008 by Walter E. Brown.  All rights reserved.

- FIN