Modern C++: What You Need to Know

Modern C++: What You Need to Know

Modern C++: What You Need to Know 2-661 Herb Sutter Partner Program Manager Modern C++: What You Need to Know 2-661 Herb Sutter Partner Program Manager Agenda Updates: ISO C++, VC++ roadmap Modern C++: What you need to know What you need to know next A Living Language C++98 (major) C++03 (TC, bug fixes only) C++11 (major)

C++14 (minor) C++17 (major) You are here 98 99 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 File System TS Library TR (aka TS) Performance TR Lib Fundamentals TS Networking TS Concepts TS Array Exts. TS + more (modules, ) Tx Memory TS Concurrency TS Parallelism TS VC++ Conformance Update VC++ 2013

Preview VC++ 2013 RTM Explicit conversion operators Non-static data member initializers __func__ Extended sizeof Thread-safe function local static init Inline namespaces constexpr (incl. ctors, literal types) = default Implicit move generation

alignof alignas Universal character names in literals Expression SFINAE Raw string literals VC++ Nov 2013 CTP Function template default arguments = delete Ref-qualifiers: & and && for *this noexcept (unconditional) noexcept (incl. conditional) C++11

preprocessor (incl. C++98 & C11) Delegating constructors using aliases C++14 libs: type aliases C++14 decltype(auto) Inheriting constructors char16_t, char32_t Attributes C++98 two-phase lookup Uniform init & initializer_lists C99 variable decls C99 _Bool

C++14 auto function return type deduction User-defined literals thread_local C++14 generalized constexpr Variadic templates C99 compound literals C++14 generic lambdas (partial) C++14 generalized lambda capture Unrestricted unions C++14 variable templates

C++14 libs: cbegin/ greater<>/make_uni que C99 designated initializers C++TS? async/await (partial) C++14 libs: std:: user-defined literals constexpr (except ctors, literal types) C++TS concepts lite VC++ Conformance Update High confidence Med confidence VC++ 2013

Preview VC++ 2013 RTM Explicit conversion operators Non-static data member initializers __func__ Extended sizeof Thread-safe function local static init Inline namespaces constexpr (incl. ctors, literal types) = default Implicit move generation

alignof alignas Universal character names in literals Expression SFINAE Raw string literals VC++ Nov 2013 CTP VC++ CTP.next (upcoming) Function template default arguments = delete Ref-qualifiers: & and && for *this noexcept (unconditional) noexcept

(incl. conditional) C++11 preprocessor (incl. C++98 & C11) Delegating constructors using aliases C++14 libs: type aliases C++14 decltype(auto) Inheriting constructors char16_t, char32_t Attributes C++98 two-phase lookup Uniform init & initializer_lists

C99 variable decls C99 _Bool C++14 auto function return type deduction User-defined literals thread_local C++14 generalized constexpr Variadic templates C99 compound literals C++14 generic lambdas (partial) C++14 generalized lambda capture Unrestricted unions

C++14 variable templates C++14 libs: cbegin/ greater<>/make_uni que C99 designated initializers C++TS? async/await (partial) C++14 libs: std:: user-defined literals constexpr (except ctors, literal types) C++TS concepts lite Agenda Updates: ISO C++, VC++ roadmap Modern C++: What you need

to know What you need to know next FAQ #1: When should I use C++? FAQ #2: What should I know about C++ if Im a {Java|C#|Javascript|Python| } dev? Use C++ for A B C++ cross-platform portability and compatibility Share model code across mobile and client platforms (native UI per platform) Access rich portable C++ libraries Some highlights: Value types by default Determinis

m by default Contiguous by default high performance and full control Memory layout control: Essential for high performance Determinism control: Prompt cleanup/release + next point full access to hardware and OS resources Graphics: DirectX, OpenGL Vector Units: Vectorization and /Qvec GPU for computation (GPGPU): C++ AMP & upcoming Parallelism TS Modern C++ is not C++98: Clean + safe But modern C++ is still C++: Flexible + fast Whats different: At a glance Then: C++98 code circle* p = new circle( 42 );

vector v = load_shapes(); for( vector::iterator i = v.begin(); i != v.end(); ++i ) { if( *i && **i == *p ) cout << **i << is a match\n; } // later, possibly elsewhere for( vector::iterator i = v.begin(); i != v.end(); ++i ) { delete *i; } delete p; Whats different: At a glance auto type deduction T* shared_ptr new make_unique or make_shared Then: C++98 code Now: Modern C++ circle* p = new circle( 42 ); auto p = make_shared( 42 ); vector v = load_shapes();

auto v = load_shapes(); for( vector::iterator i = v.begin(); i != v.end(); ++i ) { if( *i && **i == *p ) cout << **i << is a match\n; } range-for for( auto& s : v ) { if( s && *s == *p ) cout << *s << is a match\n; } // later, possibly elsewhere for( vector::iterator i = v.begin(); i != v.end(); ++i ) { delete *i; not exception-safe } missing try/catch, delete p; __try/__finally no need for delete automatic lifetime management exception-safe Example: Compute arithmetic mean of numbers

Python C++14 + concepts def mean(seq): n = 0.0 for x in seq: n += x return n / len(seq) auto mean(const Sequence& seq) { auto n = 0.0; for (auto x : seq) n += x; return n / seq.size(); } automatic return type deduction using a concept (note: not yet VC++) Types: Can express all, value types are the default Category Value types Java C#

Built-in types only Built-in types struct Val { } // bitcopy only JS C++ Built-in types class val { }; // any copying semantics Types: Can express all, value types are the default Category Java C# Value types Built-in types only Built-in types struct Val { } // bitcopy only

Reference types class foo : ifoo { @Override public int bar() { } } class Foo : IFoo { public override int Bar() { } } Interfaces interface ifoo { int bar(); } interface IFoo { int bar(); } JS C++ Built-in types class val { }; // any copying semantics class foo {

public: int bar() override { } foo(foo&) =delete; void operator=(foo&) =delete; }; class ifoo { public: virtual int bar() =0; foo(foo&) =delete; void operator=(foo&) =delete; }; Types: Can express all, value types are the default Category Java C# Value types Built-in types only Built-in types struct Val { } // bitcopy only Reference types class foo : ifoo { @Override

public int bar() { } } class Foo : IFoo { public override int Bar() { } } Interfaces interface ifoo { int bar(); } interface IFoo { int bar(); } Generic types class Map {} // type-erased, all virtual class Map {} // all virtual calls

JS C++ Built-in types class val { }; // any copying semantics class foo { public: int bar() override { } foo(foo&) =delete; void operator=(foo&) =delete; }; class ifoo { public: virtual int bar() =0; foo(foo&) =delete; void operator=(foo&) =delete; }; template class map { }; // direct calls, (partial) specialization Types: Can express all, value types are the default Category Java C#

Value types Built-in types only Built-in types struct Val { } // bitcopy only Reference types class foo : ifoo { @Override public int bar() { } } class Foo : IFoo { public override int Bar() { } } Interfaces Generic types Optional types Dynamic types interface ifoo { int bar();

} class Map {} // type-erased, all virtual Integer i = new Integer(10); JS C++ Built-in types class val { }; // any copying semantics class foo { public: int bar() override { } foo(foo&) =delete; void operator=(foo&) =delete; }; interface IFoo { int bar(); } class ifoo { public: virtual int bar() =0; foo(foo&) =delete; void operator=(foo&) =delete;

}; class Map {} // all virtual calls template class map { }; // direct calls, (partial) specialization int? i = 10; var i = 10; boost::optional i = 10; dynamic x = str; x = 10; var x = string; x = 10; boost::any x = string; x = 10; Value types & move efficiency set load_huge_data() { set ret;

// load data and populate ret return ret; } widgets = load_huge_data(); Matrix operator+( const Matrix&, const Matrix& ); m4 = m1+m2+m3; efficient, no deep copies efficient, no deep copy clean semantics of value types + efficiency of reference types If you must pick one: The most important C++ feature? } if (auto x = ) { } int do_work() {

auto x = ; } class widget { gadget g; }; Said by many, but quoting Roger Orr Default Lifetime: Scoped = Efficient + Exception Safe class widget { private: gadget g; public: void draw(); }; all types are IDisposable lifetime automatically tied to enclosing object no leak, exception safe automatic propagation, as if widget.dispose()

{ g.dispose(); } void f() { lifetime automatically widget w; tied to enclosing scope ::: constructs w, including the w.g gadget member w.draw(); ::: automatic destruction } and deallocation for w and w.g automatic exception safety, as if finally { w.g.dispose(); w.dispose(); } Destructors: Deterministic cleanup C++ has always had Dispose built in as a first-class feature, integrated throughout the language All types have Dispose (aka MyType::~MyType()) automatically generated by default, including

chaining Object lifetimes are scoped by default: to functions (implicit finally/using) to other objects (automatic Dispose chaining) Default: Code is efficient and deterministic by 1. Allocate in a scope (stack, or object) Declarative Deterministic Safe by construction { widget a; gadget b; vector c; ::: } c b a 2. Allocate on heap with make_{unique|shared} vs. GC everything Still declarative Still deterministic Still safe by construction The smart pointers themselves

are objects that are owned in some scope Everything is owned by someone Real arrays If youre serious about performance, youll love arrays Not just Lists and ArrayLists Disclaimer/context: Of course, dont forget your other data structures! Trees, graphs, hash tables all cool where appropriate stac k hea p heap c ptr

ptr ptr a b arr A Contents are not contiguous class widget { } Java/C# var arr = new ArrayList(); arr.Add( new widget() ); // etc. class widget { }; C++ vector> arr; arr.push_back( make_unique() ); // etc. stac k hea p heap

hea p stac k c ptr ptr ptr a b arr A Contents are not contiguous c b a arr B Contents contiguous class widget { } Java/C#

var arr = new ArrayList(); arr.Add( new widget() ); // etc. // not possible for class types class widget { }; C++ vector> arr; arr.push_back( make_unique() ); // etc. class widget { }; vector arr{ a, b, c }; stac k hea p heap hea p stac k

stac k c ptr ptr ptr a b arr A Contents are not contiguous c b a arr B var arr = new ArrayList(); arr.Add( new widget() ); // etc. Contents contiguous // not possible for class types // not possible for class

types class widget { }; C++ vector> arr; arr.push_back( make_unique() ); // etc. C Contents contiguous class widget { } Java/C# c b a class widget { }; vector arr{ a, b, c }; class widget { }; array arr{ a, b, c }; Real arrays (Reprise) If youre serious about

performance, youll love arrays Not just Lists and ArrayLists In C# in particular, there are tricks possible: Use pointers to structs in unsafe code Allocate structs in generic wrapper objects But they are tricks that work against the language and runtime, so they come at significant cost Sample Machine: Samsung tablet, 32K L1D$, 4M L2$ Access patterns array, vector list, tree, graph, You can see it trying to prefetch, scrambling madly to stay ahead and keep the pipeline full! matter Linear = not bad

Random = awful Arrays (real arrays) Smaller = further left, faster Often on lower curves = faster Node-based pointer- chasing data structures Bigger = further right, How much would you pay for a CPU with MB of cache? You have one in your pocket if you know how to use it. Example: Game performance Why real arrays matter Example drawn from Data Locality by Bob

Nystrom http://gameprogrammingpatterns.com/datalocality.html Bob Nystrom: Whats different? Original code class GameEntity { AIComponent* ai_; PhysicsComponent* physics_; RenderComponent* render_; ::: }; vector entities; for(auto& e : entities) { e->ai()->update(); } for(auto& e : entities) { e->physics()->update(); } for(auto& e : entities) { e->render()->update(); } ::: // other game loop machinery Whats different? Original code Fifty times faster class GameEntity { AIComponent* ai_;

PhysicsComponent* physics_; RenderComponent* render_; ::: }; class GameEntity { AIComponent* ai_; PhysicsComponent* physics_; RenderComponent* render_; ::: }; vector entities; vector entities; vector cai; vector cphysics vector crender; for(auto& e : entities) { e->ai()->update(); } for(auto& e : entities) { e->physics()->update(); } for(auto& e : entities) { e->render()->update(); } ::: // other game loop machinery for(auto& e : cai) { e.update(); } for(auto& e : cphysics) { e.update(); } for(auto& e : crender) { e.update(); } ::: // other game loop machinery

Note: GameEntity is undisturbed Just storing the objects in a different order (!) Whats different? class GameEntity { AIComponent* ai_; PhysicsComponent* physics_; RenderComponent* render_; ::: }; class GameEntity { AIComponent* ai_; PhysicsComponent* physics_; RenderComponent* render_; ::: }; vector entities; vector entities; vector cai; vector cphysics vector crender;

for(auto& e : entities) { e->ai()->update(); } for(auto& e : entities) { e->physics()->update(); } for(auto& e : entities) { e->render()->update(); } ::: // other game loop machinery for(auto& e : cai) { e.update(); } for(auto& e : cphysics) { e.update(); } for(auto& e : crender) { e.update(); } ::: // other game loop machinery Bob Nystrom: Example: Array vs. linked list for mid insert/delete Doing the Element Shuffle, a new dance craze sweeping the nation Why real arrays can surprise you Original benchmark from Jon Bentley

(Programming Pearls). Slides and measurements from Bjarne Stroustrup (GoingNative 2013 & Make Simple Things Simple) Free store info data Array vs. linked list for mid insert/delete Generate N random integers and insert them into a sequence so that each is inserted in its proper position in the numerical order. 5 1 4 2 gives: 5 15 145 1245 Remove elements one at a time by picking a random position in the sequence and removing the element there. Positions 1 2 0 0 gives 1245 145 14 4 The sequence grows incrementally For which N is it better to use a linked list than an array? Array vs. linked list for mid

insert/delete sequence test 5000 4500 4000 3500 Seconds 3000 vector 2500 list 2000 preallocated list 1500 1000 500 0 1 2

3 4 *100,000 elements 5 Vector beats list massively for insertion and deletion For small elements and relatively small numbers (up to 500,000 on my machine) Your mileage will vary Array vs. linked list for mid insert/delete Free store Space: The amount of memory used differs dramatically info List uses 4+ words per element Vector uses 1 word per element data Allocation: An unoptimized list does more allocations

One per element Can be eliminated by pre-allocation Access order: Memory access is relatively slow Unpredictable memory access gives many more cache misses Find the insertion and deletion points Linear search Use a map? This completely dominates But then we could use binary search and indexed access for a vector Also: this misses the point. Dont just optimize for the exercise Array vs. linked list vs. map Measure! Implications: Dont store data unnecessarily. Keep data compact. Access memory in a predictable manner. Your intuition is not

reliable Complexity theory is only a very rough guide 4500 4000 3500 seconds 3000 vector list list (preallocate) map 2500 2000 1500 1000 500 0 1 2 3 4

5 What collection types do I use? By default, use vector Contiguous by default Dynamically resizes to fit If you want to avoid using the heap entirely and dont need to change the number of elements, consider std::array For dictionary lookup, use: map (tree-based) unordered_map (hash-based) But: What about heterogeneous containers? Typical answer is: Same memory layout as C#/etc. nodebased collections container< smart_ptr > Owning: Prefer unique_ptr, shared_ptr

vector< unique_ptr > shapes; Non-owning: * vector< shape* > shapes; (Because you can) Loops & algorithms for/while/do std:: algorithms [&] lambda functions Then Now for( auto i = v.begin(); i != v.end(); ++i ) { ::: ::: arbitrary length lambda ::: bodies, just put the loop } for_each( begin(v), end(v), []( string& s ) { ::: for_each to visit each element :::

::: } ); body inside the lambda auto i = v.begin(); for( ; i != v.end(); ++i ) { if (*i > x && *i < y) break; } find_if to find a match auto i = find_if( begin(v), end(v), [](int i) { return i > x && i < y; } ); Speaking of STL Parallel STL A convergence of PPL, TBB, AMP, CUDA, Thrust Implementation s underway by Microsoft, Nvidia, In progress: Parallel STL TS Example: Word count string s = ... ; int num_words =

inner_product( vec, // in parallel (incl. vector lanes) begin(s), end(s)-1, begin(s)+1, // for every pair of chars 0, plus<>(), // start at 0 and add 1 [](char left, char right) { return isspace(left) && ! isspace(right); } ); // every time we start a word if( !isspace(s[0]) ) ++num_words; Microsoft prototype coming next week: https://parallelstl.codeplex.com Includes all parallel algorithms & std::par. Future release will add std::vec. Agenda Updates: ISO C++ VC++ roadmap Modern C++: What you need to know What you need to know next One C++ 2014-15: Multiple C++14 complete implementations My personal estimates, not official: Clang: Releasing every 6-7 months (Jun/Dec), likely to make 14 in 14. GCC: Releasing every spring, 4.9 may not get all the way (?),

but if not then the next one seems likely to make 14 in justpast-14. VC++: Moving fast now, ETA for full conformance forthcoming (will keep you posted). Targeting whole C++14 wave incl. Concepts. GoingNative 2012 C++s biggest conference ever Sold out, 18 countries, 23 states Global live webcast: Over 20,000 viewers Global on demand: Over 600,000 viewers GoingNative 2013 And we did it again! Sold out, 10 countries, 26 states Global live webcast: Over 20,000 viewers Global on demand: Over 1,000,000 viewers GoingNative 2014

? GoingNative++ = larger & deeper >10x content: 5 days x ~5 tracks x 5+ talks CppCon 2014 estimate: 150+ full- and half-length talks Invited talks/panels and domain experts + Lightning talks + Evening events and unconference time Call for Submissions open now: cppcon.or g libraries & frameworks functional programming concepts & generic programmin g

parallelism & multiprocessin g C++11 & C++14 real-world app experience reports high-perf & low-latency computing industry-specific (mobile, embedded, game, trading, scientific, robotics, ) tools & process es & more Your Feedback is Important Fill out an evaluation of this session and help shape future events.

Scan the QR code to evaluate this session on your mobile device. Youll also be entered into a daily prize drawing! 2014 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Recently Viewed Presentations

  • U.S. Department of the Interior Office of Natural

    U.S. Department of the Interior Office of Natural

    Suppose that fiscal year qualified OCS revenues are $96 million, $12 million to the LWCF and $36 million of which would be allocated to the Gulf producing States. Applying the inverse distance formula, the $36 million would be allocated to...
  • Wetland Policy - capf.ca

    Wetland Policy - capf.ca

    GOA Other titles: Arial Calibri Times New Roman My Master 1_My Master Office Theme 1_Office Theme 2_Office Theme 3_Office Theme 4_Office Theme 5_Office Theme 6_Office Theme 7_Office Theme 8_Office Theme 9_Office Theme 10_Office Theme 11_Office Theme Alberta Wetland Policy: A...
  • The Arthropods:

    The Arthropods:

    Evolution of arthropods has resulted in an increasing divergence of body forms, behaviors, and habitats between immature and adult stages. Ex: Larval crabs feed on plankton, adult crabs prowl sandy bottoms for live prey. Ex: Caterpillar feeds on leafy vegetables,...
  • European Exploration and Colonization of the New World: The ...

    European Exploration and Colonization of the New World: The ...

    The New World Empires of Portugal and Spain The Treaty of Tordesillas Columbus's voyage intensified rivalry between Portugal and Spain Both countries claimed the right to newly-discovered lands Pope arranged a settlement The Portuguese Amerigo Vespucci, 1st to claim what...
  • Seedless Table Grape Variety Evaluation Grown on VSP Training ...

    Seedless Table Grape Variety Evaluation Grown on VSP Training ...

    Farmers and growers that sell agricultural crops directly to the consumers are looking for new crops to expand their marketing opportunities. The purpose of the project was to look at sixteen seedless table grape cultivars to see which cultivars are...
  • FACS Exploration Model A

    FACS Exploration Model A

    Learn about pattern envelope and guide sheet. Measure for correct size of pattern. Go over information on lengthwise and crosswise grain. Learn about pattern markings . Learn how to correctly lay out, pin and cut out a pattern. McCalls pattern...
  • How successful were &#x27;Sit-ins&#x27; and &#x27;Freedom Rides&#x27; as campaign ...

    How successful were 'Sit-ins' and 'Freedom Rides' as campaign ...

    Sit-Ins. In Feb 1960, 4 black students in Greensboro, North Carolina, decided to hold a sit-in to integrate a local lunch counter. They were joined by 27 more the next day and on the 5th day, there were over 300...
  • Database Models: Flat Files and the Relational Database

    Database Models: Flat Files and the Relational Database

    Database Models: Flat Files and the Relational Database Objectives: Understand the fundamental structure of the relational database model Learn the circumstances under which it is a better choice than the flat file What is a database? Structured Data Procedures for...