Sie sind auf Seite 1von 51

Introduction to C++11 and its use inside Qt

Olivier Goart February 2013

1/43

Introduction to C++11 and its use inside Qt

About Me

http://woboq.com http://code.woboq.org

2/43

Introduction to C++11 and its use inside Qt

History
1979: 1983: 1991: 1998: 2003: 2005: 2011: 2012:
3/43

C With classes C++ Qt development begins (Qt 1.0 in 1995) C++98 - First standardized C++ C++03 - Only few corrections Qt 4.0 C++11 Qt 5.0

Introduction to C++11 and its use inside Qt

Goals of C++11
From the C++11 FAQ:

Make C++ a better language for systems programming and library building
that is, to build directly on C++s contributions to programming, rather than providing specialized facilities for a particular sub-community (e.g. numeric computation or Windows-style application development).

Make C++ easier to teach and learn


through increased uniformity, stronger guarantees, and facilities supportive of novices (there will always be more novices than experts).

4/43

Introduction to C++11 and its use inside Qt

Rules of Thumbs
From the C++11 FAQ:

Maintain stability and compatibility Prefer libraries to language extensions Prefer generality to specialization Support both experts and novices Increase type safety Improve performance and ability to work directly with hardware Fit into the real world
5/43 Introduction to C++11 and its use inside Qt

Example
1 2 3 4 5 6 7

QString processString ( const QString & str ) { enum State { Ok , Cancel }; QVector < QPair < State , QString > > stack ; stack . append ({ State :: Ok , str }); // ... }

What is specic to C++11 in this code?

6/43

Introduction to C++11 and its use inside Qt

Example
1 2 3 4 5 6 7

QString processString ( const QString & str ) { enum State { Ok , Cancel }; QVector < QPair < State , QString > > stack ; stack . append ({ State :: Ok , str }); // ... }

What is specic to C++11 in this code? use of bracket initilizer

6/43

Introduction to C++11 and its use inside Qt

Example
1 2 3 4 5 6 7

QString processString ( const QString & str ) { enum State { Ok , Cancel }; QVector < QPair < State , QString > > stack ; stack . append ({ State :: Ok , str }); // ... }

What is specic to C++11 in this code? use of bracket initilizer use of >> without a space

6/43

Introduction to C++11 and its use inside Qt

Example
1 2 3 4 5 6 7

QString processString ( const QString & str ) { enum State { Ok , Cancel }; QVector < QPair < State , QString > > stack ; stack . append ({ State :: Ok , str }); // ... }

What is specic to C++11 in this code? use of bracket initilizer use of >> without a space Scoped State::Ok

6/43

Introduction to C++11 and its use inside Qt

Example
1 2 3 4 5 6 7

QString processString ( const QString & str ) { enum State { Ok , Cancel }; QVector < QPair < State , QString > > stack ; stack . append ({ State :: Ok , str }); // ... }

What is specic to C++11 in this code? use of bracket initilizer use of >> without a space Scoped State::Ok use of local type State as template parameter
6/43 Introduction to C++11 and its use inside Qt

New Features

7/43

Introduction to C++11 and its use inside Qt

auto

1 2 3 4 5 6

QString Obj :: foo ( int blah ) { QHash < int , QString > dict = bar (); auto it = dict . find ( blah ); // ... }

8/43

Introduction to C++11 and its use inside Qt

Member Initializers

1 2 3 4 5 6 7

class X { // ... private : bool m_enabled = false ; int m_state = 0; QByteArray m_name = " None " ; }

9/43

Introduction to C++11 and its use inside Qt

Range Based for

1 2 3 4 5 6

bool Obj :: foo ( const QStringList & list ) { for ( const QString & it : list ) { // ... } }

10/43

Introduction to C++11 and its use inside Qt

Uniform Initialisation
In C++98
1 2 3 4 5 6 7 8

int b (1); // variable definition QVariant c (); // function declaration QVariant d ( QString ()); // oops QPoint p (1 ,2); int i = {2}; // yes , you can do that QString a [] = { " foo " , " bar " }; // ok // QVector < QString > v = { " foo " , " bar " }; // error

11/43

Introduction to C++11 and its use inside Qt

Uniform Initialisation
In C++11
1 2 3 4 5 6 7 8

int b {1}; // variable definition QVariant c {}; // default constructor QVariant d { QString ()}; // Works as expected QPoint p {1 ,2}; int i = {2}; // = is optional QString a [] { " foo " , " bar " }; QVector < QString > v = { " foo " , " bar " }; // works

12/43

Introduction to C++11 and its use inside Qt

Uniform Initialisation
In C++11
1 2 3 4 5 6 7 8 9 10

struct X x1 = X x2 = X* p =

X { int a , b ; }; X {1 ,2}; {1 ,2}; // the = is optional new X {1 ,2};

struct D : X { D ( int x , int y , int z ) : X {x , y } , c { z } { /* ... */ }; int c ; };

13/43

Introduction to C++11 and its use inside Qt

Uniform Initialisation
In C++11
1 2 3 4 5 6 7 8 9 10

X foo ( const X & a ) { X b { a }; return {2 ,3}; } foo ({4 ,5}); X x5 {4.2 , 4.5} // error : narrowing

// using initializer_list constructor ( from Qt 4.8) QVector <X > { {1 ,2} , {2 ,4} , {4 ,5} };

14/43

Introduction to C++11 and its use inside Qt

initializer_list

1 2 3 4 5 6 7 8 9

# ifdef Q _ C O M P I L E R _ I N I T I A L I Z E R _ L I S T S template < typename T > QVector <T >:: QVector ( std :: initializer_list <T > args ) { d = Data :: allocate ( args . size ()); copyConstruct ( args . begin () , args . end () , d - > begin ()); d - > size = args . size (); } # endif

15/43

Introduction to C++11 and its use inside Qt

C K&R syntax
1 2 3 4 5 6

int plus (x , y ) int x ; int y ; { return x + y ; }

16/43

Introduction to C++11 and its use inside Qt

Lambda

17/43 Introduction to C++11 and its use inside Qt

Lambda

[foo] (int a) -> int { return a + foo; } Capture: Variables that you capture
Parametter list: The perametters of the function Return type (optional) Function body

18/43

Introduction to C++11 and its use inside Qt

Lambda
[foo] (int a) -> int { return a + foo; }
struct { double foo; int operator()(int a) { return a + foo; } }

18/43

Introduction to C++11 and its use inside Qt

Lambda Example

1 2 3 4 5

QList < int > f ( const QList < int > & list , double foo ) { auto functor = [ foo ]( int a ) { return a + foo ; }; return QtConcurrent :: mapped ( list , functor ); }

19/43

Introduction to C++11 and its use inside Qt

Lambda capture
1 2 3 4 5 6 7 8 9 10 11 12 13

int a {1} , b {2} , c {3}; // a by value , b by reference auto f1 = [a , & b ]() { b = a ; }; // everything by reference auto f2 = [&]() { b = a ; }; // everything by value auto f3 = [=]() { return a + c ; }; // everything by value , b by reference auto f4 = [= ,& b ]() { b = a + c ; };

20/43

Introduction to C++11 and its use inside Qt

Lambda Example (Qt5)


1 2 3 4 5 6 7 8 9 10 11 12

void Doc :: saveDocument () { QFileDialog * dlg = new QFileDialog (); dlg - > open (); QObject :: connect ( dlg , & QDialog :: finished , [ dlg , this ]( int result ) { if ( result ) { QFile file ( dlg - > selectedFiles (). first ()); // ... } dlg - > deleteLater (); }); }

21/43

Introduction to C++11 and its use inside Qt

Function Declaration
1 2 3 4 5 6 7 8

struct Foo { enum State { /* ... */ }; /* ... */ State func ( State ); }; // Error State Foo :: func ( State arg ) { /* ... */ }

22/43

Introduction to C++11 and its use inside Qt

Function Declaration
1 2 3 4 5 6 7 8

struct Foo { enum State { /* ... */ }; /* ... */ State func ( State ); }; // Error State Foo :: func ( State arg ) { /* ... */ }

Alternative function syntax


1 2

auto Foo :: func ( State arg ) -> State { /* ... */ }

22/43

Introduction to C++11 and its use inside Qt

decltype

1 2 3 4 5 6 7 8 9 10

template < typename A , typename B > auto dotProduct ( A vect_a , B vect_b ) -> decltype ( vect_a [0]* vect_b [0]) { /* ... */ }

QList < int > a { /* ... */ }; QVector < float > b { /* ... */ }; auto p = dotProduct (a , b );

23/43

Introduction to C++11 and its use inside Qt

Default and Deleted function


1 2 3 4 5 6 7

struct MyObject { virtual ~ MyObject () = default ; MyObject ( int ); MyObject () = default ; int someFunction ( QObject *); int someFunction ( QWidget *) = delete ; }; # define Q_DISABLE_COPY ( Class ) \ Class ( const Class &) = delete ; \ Class & operator =( const Class &) = delete ;

1 2 3

24/43

Introduction to C++11 and its use inside Qt

Q_DECL_DELETE

1 2 3 4 5 6

struct MyObject { void myFunction ( int ); // ... private : void myFunction ( bool ) Q_DECL_DELETE ; };

25/43

Introduction to C++11 and its use inside Qt

Rvalue References
1 2 3 4 5 6 7 8 9 10 11 12 13 14

struct string { char * data ; string ( const char * str ) : data ( strdup ( str )) {} string ( const string & o ) : data ( strdup ( o . data )) {} ~ string () { free ( data ); } string & operator =( const string & o ) { free ( data ); data = strdup ( o . data ) return * this ; } }; template < class T > swap ( T &a , T & b ) { T tmp ( a ); a = b ; b = tmp ; }

26/43

Introduction to C++11 and its use inside Qt

Rvalue References
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

struct string { /* ... */ string ( const string & o ); // copy constructor string ( string && o ) // move constructor : data ( o . data ) { o . data = 0; } string & operator =( const string & o ); // copy assignme string & operator =( string && o ) // move assignment { swap ( data , o . data ); } }; template < class T > swap ( T &a , T & b ) { T tmp = std :: move ( a ); a = std :: move ( b ); b = std :: move ( tmp ); }
Introduction to C++11 and its use inside Qt

27/43

Rvalue References

1 2 3 4 5 6 7 8 9

X a; X f (); X & r1 = a ; X & r2 = f (); // bind r1 to a ( an lvalue ) // error : f () is an rvalue ; can t bind

X && rr1 = f (); // ok : bind rr1 to temporary X && rr2 = a // error : bind a is an lvalue X && rr3 = std :: move ( a ) // ok

28/43

Introduction to C++11 and its use inside Qt

Move Sementic

1 2 3 4 5 6 7 8 9 10

# ifdef Q _ C O M P I L E R _ R V A L U E _ R E F S inline QString :: QString ( QString && other ) : d ( other . d ) { other . d = Data :: sharedNull (); } inline QString :: QString & operator =( QString && other ) { qSwap (d , other . d ); return * this ; } # endif

29/43

Introduction to C++11 and its use inside Qt

Perfect Forwarding
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

template < class T > class QSharedPointer { /* ... */ # if defined ( Q _ C O M P I L E R _ R V A L U E _ R E F S ) \ && defined ( Q _ C O M P I L E R _ V A R I A D I C _ T E M P L A T E S ) template < typename ... Args > static QSharedPointer <T > create ( Args && ... args ) { QSharedPointer <T > result ( Qt :: Uninitialized ); result . d = Private :: create (& result . value ); // now initialize the data new ( result . data ()) T ( std :: forward < Args >( args )...); result .d - > setQObjectShared ( result . value , true ); return result ; } # endif
Introduction to C++11 and its use inside Qt

30/43

constexpr

1 2 3 4 5 6 7 8 9

switch ( btn ) { case Qt :: LeftButton : /* ... */ break ; case Qt :: RightButton : /* ... */ break ; // error ? the operator | convert to QFlags case Qt :: LeftButton | Qt :: RightButton : /* ... */ break ; default : /* ... */ }

31/43

Introduction to C++11 and its use inside Qt

constexpr
1 2 3 4 5 6 7 8 9 10 11 12

template < typename Enum > class QFlags { int i ; public : constexpr QFlags ( Enum e ) i { e } {} constexpr operator int () { return i ; } // ... }; # define Q _ D E C L A R E _ O P E R A T O R S _ F O R _ F L A G S ( ENUM ) \ constexpr inline QFlags < ENUM > operator |( ENUM a , ENUM b ) \ { return QFlags ( ENUM ( a | b )); }

32/43

Introduction to C++11 and its use inside Qt

constexpr
1 2 3 4 5 6 7 8 9 10 11 12

template < typename Enum > class QFlags { int i ; public : Q_DECL_CONSTEXPR QFlags ( Enum e ) i { e } {} Q_DECL_CONSTEXPR operator int () { return i ; } // ... }; # define Q _ D E C L A R E _ O P E R A T O R S _ F O R _ F L A G S ( ENUM ) \ Q_DECL_CONSTEXPR inline QFlags < ENUM > operator | \ ( ENUM a , ENUM b ) \ { return QFlags ( ENUM ( a | b )); }

33/43

Introduction to C++11 and its use inside Qt

Explicit Override
struct A { virtual void foo ( int ); virtual void bar ( int ) const ; }; struct B : public A { void foo ( float ); // oops void bar ( int ); // oops };

1 2 3 4

1 2 3 4

34/43

Introduction to C++11 and its use inside Qt

Explicit Override
1 2 3 4

struct A { virtual void foo ( int ); virtual void bar ( int ) const ; }; struct B void void void void }; : public A { foo () override ; // bar ( int ) override ; baz ( int ) override ; foo ( int ) override ; compilation error // compilation error // compilation error // ok

1 2 3 4 5 6 7 8 9 10

struct C : public A { void foo ( int ) final ; };

34/43

Introduction to C++11 and its use inside Qt

Explicit Override
1 2 3 4

struct A { virtual void foo ( int ); virtual void bar ( int ) const ; }; struct B void void void void };

1 2 3 4 5 6 7 8 9 10

: public A { foo () Q_DECL_OVERRIDE ; // compilation error bar ( int ) Q_DECL_OVERRIDE ; // compilation error baz ( int ) Q_DECL_OVERRIDE ; // compilation error foo ( int ) Q_DECL_OVERRIDE ; // ok

struct C : public A { void foo ( int ) Q_DECL_FINAL ; };

34/43

Introduction to C++11 and its use inside Qt

String Literals
Unicode strings
1 2 3 4 5 6 7 8

// utf -8 const char * str1 = u8 " v \ u00e6r s \ u00e5 god " ; // utf -16 const char16_t * str2 = u " v \ u00e6r s \ u00e5 god " ; // utf -32 const char32_t * str3 = U " v \ u00e6r s \ u00e5 god " ; QStringLiteral ( " Hello " ); (http://woboq.com/blog/qstringliteral.html)

35/43

Introduction to C++11 and its use inside Qt

Raw Literals

C++98
1 2

ret . replace ( QRegExp ( " (\\\\*)\" " ) , " \"\\1\\1\\^\"\" " )

Raw litteral
1 2

ret . replace ( QRegExp ( R " -( (\\*)" ) -" ) , R "( "\1\1\^"" )" );

36/43

Introduction to C++11 and its use inside Qt

enum class

1 2 3 4 5 6 7 8 9

enum Color { Blue , Red , Yellow }; enum class State { Ok , Cancel }; enum class SomeEnum ; // forward declare ( sizeof ( int )) enum OtherEnum : char {A , B }; // specify the size Color color1 = Blue , color2 = Color :: Red ; State state1 = Cancel ; // error State state2 = State :: Cancel ;

37/43

Introduction to C++11 and its use inside Qt

...
nullptr Generalized POD Generalized unions user dened litteral explicit conversion operators noexcept (Q_DECL_NOTHROW , Q_DECL_NOEXCEPT,
Q_DECL_NOEXCEPT_EXPR)

delegating constructors Inline namespace


38/43 Introduction to C++11 and its use inside Qt

Templates
Variatic template Default template arguments for function templates SFINAE for expressions Extern templates Local and unnamed types as template arguments Template aliases static_assert (Q_STATIC_ASSERT , Q_STATIC_ASSERT_X)
39/43 Introduction to C++11 and its use inside Qt

Concurrency

Memory model Thread Local Storage (thread_local) Atomic operations futures, mutexes, . . .

40/43

Introduction to C++11 and its use inside Qt

More STL Features


unordered_map (QHash) Smart pointers (unique_ptr, shared_ptr, weak_ptr) bind, function more algorithms (min, max, minmax, all_of, any_of, is_sorted, copy_if, copy_n, partition_copy, iota ...) Regular expressions Random number generation ...
41/43 Introduction to C++11 and its use inside Qt

http://abstrusegoose.com/249

42/43

Introduction to C++11 and its use inside Qt

The End
CONFIG += c++11

Questions
olivier@woboq.com

visit http://woboq.com

43/43

Introduction to C++11 and its use inside Qt

Das könnte Ihnen auch gefallen