C++11 - The new standard - Theoretische Informatik II - Friedrich

27
Features for Everybody Advanced Features Summary C++11 - The new standard Lars K¨ uhne Institut f¨ ur Informatik Lehrstuhl f¨ ur theoretische Informatik II Friedrich-Schiller-Universit¨ at Jena January 16, 2013

Transcript of C++11 - The new standard - Theoretische Informatik II - Friedrich

Features for Everybody Advanced Features Summary

C++11 - The new standard

Lars Kuhne

Institut fur InformatikLehrstuhl fur theoretische Informatik II

Friedrich-Schiller-Universitat Jena

January 16, 2013

Features for Everybody Advanced Features Summary

Overview

A little bit of history:

C++ was initially developed by Bjarne Stroustrup in 1979

first ISO Standard in 1998

replaced by the corrigendum C++03 in 2003 (only bug fixesfor the implementors)

early draft in 2005: technical report 1 (TR1)

next (and current) standard release in August, 2011: C++11

“Surprisingly, C++11 feels like a new language - the pieces just fittogether better.” Bjarne Stroustrup

Features for Everybody Advanced Features Summary

Things you won’t miss

std::auto ptr: got replaced by std::unique ptr

the export keyword

was supposed to allow separation of declaration and definitionof templatesno major compiler supportstill reserved

dynamic exception specifications

by default every function can throw anythingexceptions specifications allow to restrict thatnot enforced at compile-time, hard to use correctly

Features for Everybody Advanced Features Summary

Getting started

recognize >> as closing a template declaration,instead of >>

new keyword: noexcept

vo id f oo ( ) noexcept ;

a guarantee by the programmer to the compiler to guideoptimizations

compile-time assertions: static assert

Example (static assert)

template <typename T>vo id bar ( const T& x ) {

s t a t i c a s s e r t ( s t d : : i s i n t e g r a l <T> : : va lue ,”T must be i n t e g r a l ” ) ;

// do some a r i t hm e t i c . . .}

Features for Everybody Advanced Features Summary

default, delete, final and override

Example

c l a s s A {p u b l i c :

A( ) = d e f a u l t ;A( const A&) = d e l e t e ;v i r t u a l vo id f oo ( ) {}v i r t u a l vo id bar ( ) f i n a l {}

} ;

c l a s s B : p u b l i c A f i n a l {p u b l i c :

v i r t u a l vo id f oo ( ) o v e r r i d e ;v i r t u a l vo id bar ( ) ; // e r r o r

} ;

c l a s s C : p u b l i c B; // e r r o r

Features for Everybody Advanced Features Summary

Extern templates

in C++03 the compiler is required to instantiate everyfully-specified template

this may result in long compilation times, if the sametemplate gets instantiated in different translation units

Example

// heade rtemplate <typename T>c l a s s Foo {/∗ compi le−t ime e x p e n s i v e d e f i n i t i o n ∗/ } ;// sou r c e1 . oauto x = Foo<double >() ;// sou r c e2 . o −> comp i l e s f o r a 2nd t ime !auto x = Foo<double >() ;// s o u r c e 2 e x t e r n . o −> no i n s t a n t i a t i o n o f Foo<double>extern template c l a s s Foo<double >;auto x = Foo<double >() ;

Features for Everybody Advanced Features Summary

The problem with NULL

as inherited by C, NULL is a Makro usually expanding to 0

Example

vo id f oo ( i n t ) ;vo id f oo ( char ∗ ) ;// c a l lf oo (NULL ) ;

new null-pointer constant: std::nullptr

implicitely convertible and comparable to any pointer type

not so for integral types, except for bool

Features for Everybody Advanced Features Summary

The auto keyword

old keyword with new meaning

tells the compiler to deduce the type of the variable from itsinitialization

i n t x = 4 ; // C++98auto x = 4 ; // C++11

Serves as a convenience in cases where the type is either hard towrite...

s t d : : map<i n t , s t d : : v e c to r<double> > my map ;// C++98s t d : : map<i n t , s t d : : v e c to r<double> > : :c o n s t i t e r a t o r i t = my map . beg i n ( ) ;// C++11auto i t = my map . cbeg i n ( ) ;

Features for Everybody Advanced Features Summary

The auto keyword

...or hard to know

template <c l a s s A, c l a s s B>vo id f oo ( const A& a , const B& b) {

auto tmp = a ∗ b ;}// c a l l i n g the f u n c t i o nf oo (u , v ) ;

Inconvenient C++98 solution:

template <c l a s s A, c l a s s B, c l a s s C>vo id f oo ( const A& a , const B& b) {

C tmp = a ∗ b ;}// c a l l i n g the f u n c t i o nfoo<W>(u , v ) ;

Features for Everybody Advanced Features Summary

The auto keyword

strips off const-ness and references

i n t a = 42 ;const i n t& b = a ;auto c = b ; // i n t// e x p l i c i t e l y add on q u a l i f i e r sconst auto& d = c ; // cons t i n t&

pointers, however, are treated as types of their own

i n t ∗ a p t r = &a ;auto b p t r = a p t r ; // i n t ∗auto∗ c p t r = a p t r ; // i n t ∗

Features for Everybody Advanced Features Summary

The auto keyword and return-types

return-types can be auto as well

auto f oo ( ) −> i n t {r e t u r n 4 ;

}

requires the programmer to provide a trailing-return-type

template <c l a s s A, c l a s s B>auto f oo ( const A& a , const B& b) −> d e c l t y p e ( a ∗ b ) {

r e t u r n a ∗ b ;}

decltype is a new compile-time operator that returns the typeof the given expression

trailing-return-type especially useful with multiplereturn-statements (std::common type)

Features for Everybody Advanced Features Summary

Range-based for-loop

allows for a more compact way to express an iteration over arangean object is a range, if

1 its type either has the members begin() and end() returningvalid iterators

2 or there are functions begin(obj) and end(obj) doing so

all STL containers, regular-expression matches and initializerlists are iterable using range-based for loops

Example

s t d : : v e c to r<i n t> v ;// . . . f i l l v . . .f o r ( i n t i : v )

s t d : : cout << i << s t d : : e nd l ;f o r ( auto& i : v ) // cons t a l s o p o s s i b l e

i = i ∗ i ;

Features for Everybody Advanced Features Summary

Lambda functions

Example (What’s wrong with this picture?)

c l a s s SquareFuncto r {p u b l i c :

template <typename Sca l a r>S c a l a r operator ( ) ( const S c a l a r v a l u e ) {

r e t u r n v a l u e ∗ v a l u e ;}

} ;

template <c l a s s I t e r a t o r >vo id squa r e ( I t e r a t o r beg in , I t e r a t o r end ) {

SquareFuncto r mySquareFunctor ;s t d : : f o r e a c h ( beg in , end , mySquareFunctor ) ;

}

a lot of code to square a number

required a named entity for a one-liner

Features for Everybody Advanced Features Summary

Lambda functions

Example

template <c l a s s I t e r a t o r >vo id squa r e ( I t e r a t o r beg in , I t e r a t o r end )s td : : f o r e a c h ( beg in , end ,

[ ] ( double v a l u e ) { r e t u r n v a l u e ∗ v a l u e ; } ) ;

Definition (Lambda)

1 capture []: wildcard & and =, or named variables from scope

2 function body {}3 no return type: is deduced by the compiler

4 optional: trailing return-type

5 under the hood: the compiler defines and intantiates afull-fledged function object

Features for Everybody Advanced Features Summary

Lambda functions

Example

s t d : : map<i n t , s t d : : s t r i n g> myMap ;const i n t i d x = 3 ;// f i l l map . . .// the comp i l e r c a p t u r e s a l l the v a r i a b l e s// used i n the body by r e f e r e n c eauto lambda 1 = [&] ( ) { r e t u r n myMap [ i d x ] . s i z e ( ) > 0} ;// copy the idx , but cap tu r e the map by r e f e r e n c eauto lambda 2 = [=,&myMap ] ( ){ r e t u r n myMap [ i d x ] . s i z e ( ) > 0} ;// c a l l the lambdai f ( lambda 1 ( ) )

e x i t (EXIT SUCCESS ) ;

convenient inline function-declaration

C++11-lambdas are not polymorphic (yet)

Features for Everybody Advanced Features Summary

Rvalue references

motivation: avoid creating temporaries

Example

s t d : : v e c to r<s t d : : s t r i n g> v ;v . push back ( ”C++11” ) ;

1 implicitely: calls std::string(const char*) → this creates thetemporary!

2 calls v.push back(const std::string&) →this appends a copy of the temporary

3 implicitely: calls std::string::∼string() on the temporary

unnecessary constructor and destructor call

Features for Everybody Advanced Features Summary

Rvalue references

idea: reuse the temporary for the final result

What makes a temporary/rvalue?

Definition (Lvalues and Rvalues)

inspired by the side of = they are usually found

i n t n = 3 ; // n i s an l−v a l u e5 = n + 7 ; // 5 i s an r−v a l u e ( compi le−t ime e r r o r )

lvalues (their address) still exists after the statement

rvalues do not exist anymore after the statement(even though one might have kept the address)

Features for Everybody Advanced Features Summary

Rvalue references

are defined with &&

mutable rvalues (exclusively!) bind to rvalue-references →special treatment for temporaries

binding-rules

& const & && const &&

lvalue x x x x

const-lvalue x x

rvalue x x x

const-rvalue x x

Features for Everybody Advanced Features Summary

Rvalue references

Example (Overload resolution)

vo id f oo ( s t d : : s t r i n g &);vo id f oo ( const s t d : : s t r i n g &);vo id f oo ( s t d : : s t r i n g &&);vo id f oo ( const s t d : : s t r i n g &&);

foo ( l v a l u e ) ; // vo i d foo ( s t d : : s t r i n g &);f oo ( c o n s t l v a l u e ) ; // vo i d foo ( con s t s t d : : s t r i n g &);f oo ( r v a l u e ) ; // vo i d foo ( s t d : : s t r i n g &&);f oo ( c o n s t r v a l u e ) ; // vo i d foo ( con s t s t d : : s t r i n g &&);

Easy rules:

rvalues prefer rvalue-references

lvalues prefer lvalue-references

must respect const-ness

Features for Everybody Advanced Features Summary

Rvalue references

1 in practice: const & und &&

2 copy-/move-constructors and assignment-operators

3 the compiler recognizes temporaries by resolving them to&&-overloads → basis for move semantic

Example (Move-semantic methods)

c l a s s Foo {p u b l i c :

Foo ( ) ;Foo ( const Foo&);Foo& operator=(const Foo&);// move−c o n s t r . and ass ignment−op .Foo ( Foo&&);Foo& operator=(Foo&&);

} ;Foo x ( Foo ( ) ) ; // c a l l s Foo ( Foo&&)

Features for Everybody Advanced Features Summary

Rvalue references

Example (Move Semantics)

c l a s s AlsoMovable {} ;c l a s s Moveable {

p u b l i c :Moveable ( s t d : : s i z e t s i z e )

: b i gA r r a y (new double [ s i z e ] ) {}

Moveable ( Moveable&& othe r ): b i gA r r a y ( o t h e r . b i gA r r a y ) ,

am( s td : : move ( o th e r . am) ) {o th e r . b i gA r r a y = s td : : n u l l p t r ;

}

˜Moveable ( ) { d e l e t e b i gA r r a y ;}p r i v a t e

double∗ b i gA r r a y ;AlsoMovable am ;

}

Features for Everybody Advanced Features Summary

Rvalue references

rvalue-references are useful when there is more to move thanjust basic data types (int, float, pointers, ...)

big chunks of dynamically allocated memory(moveable) members of some other class type

the STL is now move-enabled:container-classes provide move-insertionstd::unique ptr is move-only

not every moveable can be detected by the compiler

Example (user-guided moving)

template <c l a s s T>vo id swap (T& x , T& y ) {

T tmp( s td : : move ( x ) ) ;x = s td : : move ( y ) ;y = s td : : move ( tmp ) ;

}

std::move turns lvalue-references into rvalue-references

Features for Everybody Advanced Features Summary

Variadic Templates

templates can now have an arbitrary number of arbitrary types

Definition (Parameter Pack)

indicated with the ellipsis operator: ...

1 Template: holds variadic template parameters

2 Function: holds the corresponding function arguments

Example

template <c l a s s . . . Types> c l a s s t u p l e ;

template <c l a s s T, c l a s s . . . Args>s t d : : s h a r e d p t r<T> make shared ( Args &&.. . a r g s ) ;

template <c l a s s T, s td : : s i z e t . . . Dims>c l a s s Mult iDimArray ;

Features for Everybody Advanced Features Summary

Variadic Templates - Unpacking: ...

Example

template <c l a s s . . . Args> c l a s s CountArgs ;

template <c l a s s T, c l a s s . . . Args>c l a s s CountArgs<T, Args . . . > {

p u b l i c :const s t a t i c i n t v a l u e =CountArgs<Args . . . > : : v a l u e + 1 ;

} ;// no arguments matches , tootemplate <> c l a s s CountArgs<> {

p u b l i c : const s t a t i c i n t v a l u e = 0 ;} ;

CountArgs<i n t , f l o a t , double > : : v a l u e ; // 3

sizeof...(Args) does the same

Features for Everybody Advanced Features Summary

Variadic Templates - Unpacking patterns

the ...-operator unpacks every element according to thepattern to its left

Example

template <c l a s s T, c l a s s . . . Rest>// add cons t and & to each e l ement o f Restvo id p r i n t ( const T& obj , const Rest & . . . r e s t ) {

s t d : : cout << ob j ;// don ’ t add any th i ng to r e s tp r i n t ( r e s t . . . ) ;

}

template <c l a s s F , c l a s s . . . Types>vo id c a l l (F foo , const Types & . . . t y p e s ) {

// t r a n s l a t e s i n t o : foo ( bar ( t ype s1 ) , bar ( t ype s2 ) , . . . )f oo ( bar ( t yp e s ) . . . ) ;

}

Features for Everybody Advanced Features Summary

Still more

polymorphic function-wrappers

type-traits for meta-programming

comprehensive number-generation facilitiy

regular expressions

hash-based unordered containers

user-defined literals, initializer lists, ...

The ISO plans on publishing the next revision C++1y until 2017.There is now an official community website: isocpp.org

Features for Everybody Advanced Features Summary

Thank you!

Questions?

Overview of the new C++(C++11) - Scott Meyers

C++11 - the final draft (N3337) - ISO

cppreference.com, cplusplus.com