Complexity Anonymous Recover from Complexity Addiction

Total Page:16

File Type:pdf, Size:1020Kb

Complexity Anonymous Recover from Complexity Addiction C++14 Style 9/13/2014 Herb Sutter Herb Sutter C A Complexity Anonymous A 12-step program for good people attempting to recover from complexity addiction 2014 Herb Sutter except material otherwise referenced. 1 C++14 Style 9/13/2014 Herb Sutter C++ developers (~3M) libstdc++ developers (~30) + libc++ developers (~5-7) + Boost developers (~300?) + ISO WG21 attenders (~300?) 2014 Herb Sutter except material otherwise referenced. 2 C++14 Style 9/13/2014 Herb Sutter Occurrences of “&&” in Bjarne’s 90-min Tue keynote? 0 Value of modern C++’s simple usable defaults? Priceless “What should every C++ programmer be expected to know?” For years, there has not been a single source to point to. Now there is. In 180 pages you can read on a long plane flight. Recommend it heavily! Also a demonstration that modern C++ is simpler to teach and explain. 2014 Herb Sutter except material otherwise referenced. 3 C++14 Style 9/13/2014 Herb Sutter This talk focuses on defaults, basic styles and idioms in modern C++. “Default” != “don’t think.” “Default” == “don’t overthink.” Esp. don’t optimize prematurely. These reinforce (not compete with) the “fundamentals.” “Write for clarity and correctness first.” “Avoid premature optimization.” By default, prefer clear over optimal. “Avoid premature pessimization.” Prefer faster when equally clear. why do this for( auto i = begin(c); i != end(c); ++i ) { … use(*i); … } when you can do this for( auto& e : c ) { … use(e); … } and soon this for( e : c ) { … use(e); … } 2014 Herb Sutter except material otherwise referenced. 4 C++14 Style 9/13/2014 Herb Sutter wait, what? C++98: Modern C++: widget* factory(); unique_ptr<widget> factory(); void caller() { void caller() { widget* w = factory(); auto w = factory(); gadget* g = new gadget(); auto g = make_unique<gadget>(); use( *w, *g ); use( *w, *g ); delete g; } delete w; } red now “mostly wrong” Don’t use owning *, For “new”, use make_unique by default, new or delete. make_shared if it will be shared. Except: Encapsulated inside the implementation of low- For “delete”, write nothing. level data structures. 2014 Herb Sutter except material otherwise referenced. 5 C++14 Style 9/13/2014 Herb Sutter NB: important qualifier C++98: C++14: widget* factory(); unique_ptr<widget> factory(); void caller() { void caller() { widget* w = factory(); auto w = factory(); gadget* g = new gadget(); auto g = make_unique<gadget>(); use( *w, *g ); use( *w, *g ); delete g; } delete w; } red now “mostly wrong” Don’t use owning *, For “new”, use make_unique by default, new or delete. make_shared if it will be shared . Except: Encapsulated inside the implementation of low- For “delete”, write nothing. level data structures. C++98 “Classic”: Modern C++ “Still Classic”: void f( widget& w ) { // if required void f( widget& w ) { // if required use(w); use(w); } } void g( widget* w ) { // if optional void g( widget* w ) { // if optional if(w) use(*w); if(w) use(*w); } } auto upw = make_unique<widget>(); … f( *upw ); auto spw = make_shared<widget>(); * and & FTW … (More on parameter passing coming later…) g( spw.get() ); 2014 Herb Sutter except material otherwise referenced. 6 C++14 Style 9/13/2014 Herb Sutter Antipattern #1: Parameters Antipattern #2: Loops (Note: Any refcounted pointer type.) (Note: Any refcounted pointer type.) void f( refcnt_ptr<widget>& w ) { refcnt_ptr<widget> w = …; use(*w); for( auto& e: baz ) { } // ? auto w2 = w; void f( refcnt_ptr<widget> w ) { use(w2,*w2,w,*w,whatever); use(*w); } // ?!?! } // ?!?!?!?! Example (thanks Andrei): In late 2013, Facebook RocksDB changed from pass-by-value shared_ptr to pass-*/&. QPS improved 4 (100K to 400K) in one benchmark. http://tinyurl.com/gotw91-example FAQ: Smart Pointer Parameters — See GotW #91 (tinyurl.com/gotw91) Refcounted smart pointers are about managing the owned object’s lifetime. Copy/assign one only when you intend to manipulate the owned object’s lifetime. Any “smart pointers (or std::vectors) are slow” performance claims based on code that copies/assigns smart pointers (or std::vectors) – including passing by value or copying/assigning in loops – when copies are not needed are fundamentally flawed. Yes, this applies to your refcounted smart pointer: • shared_ptr (Boost, TR1, std::) • retain/release (Objective-C ARC, Clang 3.5) • AddRef/Release (COM and WinRT, C++/CX ^) • any other refcounting strategy you will ever see 2014 Herb Sutter except material otherwise referenced. 7 C++14 Style 9/13/2014 Herb Sutter unique_ptr<widget> factory(); // source – produces widget void sink( unique_ptr<widget> ); // sink – consumes widget void reseat( unique_ptr<widget>& ); // “will” or “might” reseat ptr void thinko( const unique_ptr<widget>& ); // usually not what you want shared_ptr<widget> factory(); // source + shared ownership // when you know it will be shared, perhaps by factory itself void share( shared_ptr<widget> ); // share – “will” retain refcount void reseat( shared_ptr<widget>& ); // “will” or “might” reseat ptr void may_share( const shared_ptr<widget>& ); // “might” retain refcount 1. Never pass smart pointers (by value or by reference) unless you actually want to manipulate the pointer store, change, or let go of a reference. Prefer passing objects by * or & as usual – just like always. Else if you do want to manipulate lifetime, great, do it as on previous slide. 2. Express ownership using unique_ptr wherever possible, including when you don’t know whether the object will actually ever be shared. It’s free = exactly the cost of a raw pointer, by design. It’s safe = better than a raw pointer, including exception-safe. It’s declarative = expresses intended uniqueness and source/sink semantics. It removes many (often most) objects out of the ref counted population. 3. Else use make_shared up front wherever possible, if object will be shared. 2014 Herb Sutter except material otherwise referenced. 8 C++14 Style 9/13/2014 Herb Sutter The reentrancy pitfall (simplified): “Pin” using unaliased local copy. // global (static or heap), or aliased local // global (static or heap), or aliased local … shared_ptr<widget> g_p … … shared_ptr<widget> g_p … void f( widget& w ) { void f( widget& w ) { g(); g(); use(w); use(w); } } void g() { void g() { g_p = … ; g_p = … ; } } void my_code() { void my_code() { auto pin = g_p; // 1 ++ for whole tree f( *g_p ); // passing *nonlocal f( *pin ); // ok, *local } // should not pass code review } The reentrancy pitfall (simplified): “Pin” using unaliased local copy. // global (static or heap), or aliased local // global (static or heap), or aliased local … shared_ptr<widget> g_p … … shared_ptr<widget> g_p … void f( widget& w ) { void f( widget& w ) { g(); g(); use(w); use(w); } } void g() { void g() { g_p = … ; g_p = … ; } } void my_code() { void my_code() { auto pin = g_p; // 1 ++ for whole tree f( *g_p ); // passing *nonlocal f( *pin ); // ok, *local g_p->foo(); // (or nonlocal->) pin->foo(); // ok, local-> } // should not pass code review } 2014 Herb Sutter except material otherwise referenced. 9 C++14 Style 9/13/2014 Herb Sutter 1. Never pass smart pointers (by value or by reference) unless you actually want to manipulate the pointer store, change, or let go of a reference. Prefer passing objects by * or & as usual – just like always. Remember: Take unaliased+local copy at the top of a call tree, don’t pass f(*g_p). Else if you do want to manipulate lifetime, great, do it as on previous slide. 2. Express ownership using unique_ptr wherever possible, including when you don’t know whether the object will actually ever be shared. It’s free = exactly the cost of a raw pointer, by design. It’s safe = better than a raw pointer, including exception-safe. It’s declarative = expresses intended uniqueness and source/sink semantics. It removes many (often most) objects out of the ref counted population. 3. Else use make_shared up front wherever possible, if object will be shared. Don’t use owning raw *, new, or delete any more, except rarely inside the implementation details of low-level data structures. Do use non-owning raw * and &, especially for parameters. Don’t copy/assign refcounted smart pointers, including pass-by-value or in loops, unless you really want the semantics they express: altering object lifetime. 2014 Herb Sutter except material otherwise referenced. 10 C++14 Style 9/13/2014 Herb Sutter 2014 Herb Sutter except material otherwise referenced. 11 C++14 Style 9/13/2014 Herb Sutter Guru Meditation Q: What does this code do? template<class Container, class Value> void append_unique( Container& c, Value v ) { if( find(begin(c), end(c), v) == end(c) ) c.push_back( move(v) ); // anything comparable to end(cont)… assert( !c.empty() ); // what type does .empty return? } // anything testable like a bool… x 2014 Herb Sutter except material otherwise referenced. 12 C++14 Style 9/13/2014 Herb Sutter Counterarguments: “Oi, but it’s unreadable!” “What’s my type?” This is a weak argument for three reasons: (Minor) It doesn’t matter to anyone who uses an IDE. (Major) It reflects bias to code against implementations, not interfaces. (Major) We already ignore actual types with templates and temporaries. template<class Container, class Value> // what type is Container? Value? void append_unique( Container& c, Value v ) // anything usable like this… { if( find(begin(c), end(c), v) == end(c) ) // what type does find return? c.push_back( move(v) ); // anything comparable to end(cont)… assert( !c.empty() ); // what type does .empty return? } // anything testable like a bool… We also ignore actual types with virtual functions, function<>, etc. With deduction you always get right type. Repetition P(lying) Example: void f( const vector<int>& v ) { vector<int>::iterator i = v.begin(); // ? } Options: void f( const vector<int>& v ) { vector<int>::iterator i = v.begin(); // error vector<int>::const_iterator i = v.begin(); // ok + extra thinking auto i = v.begin(); // ok, default } 2014 Herb Sutter except material otherwise referenced. 13 C++14 Style 9/13/2014 Herb Sutter Using deduction makes your code more robust in the face of change.
Recommended publications
  • Smart Pointers Raw Pointers (1 of 3)
    Data Abstraction & Problem Solving with C++: Walls and Mirrors Seventh Edition C++ Interlude 4 Safe Memory Management Using Smart Pointers Raw Pointers (1 of 3) • Allocate memory in free store by using new operator – Returns reference to newly created object in memory • Store reference to object in a pointer variable – Use pointer variable to access object • Copy reference to another pointer variable – Creates alias to same object Copyright © 2017, 2013, 2007 Pearson Education, Inc. All Rights Reserved Raw Pointers (2 of 3) • Use delete operator to deallocate object’s memory – Must also set to null p t r any pointer variables that referenced the object • Need to keep track number of aliases that reference an object … else results in – Dangling pointers – Memory leaks – Other errors (program crash, wasted memory, …) Copyright © 2017, 2013, 2007 Pearson Education, Inc. All Rights Reserved Raw Pointers (3 of 3) • Languages such as Java and Python disallow direct reference to objects – Use reference counting to track number of aliases that reference an object – Known as the “reference count” • Language can detect when object no longer has references – Can deallocate … known as “garbage collection” Copyright © 2017, 2013, 2007 Pearson Education, Inc. All Rights Reserved Smart Pointers (1 of 2) • C++ now supports “smart” pointers (or managed pointers) – Act like raw pointers – Also provide automatic memory management features • When you declare a smart pointer – Placed on application stack – Smart pointer references an object object is “managed” Copyright © 2017, 2013, 2007 Pearson Education, Inc. All Rights Reserved Smart Pointers (2 of 2) • Smart-pointer templates – shared_p t r – provides shared ownership of object – unique_p t r – no other pointer can reference same object – weak_p t r – reference to an object already managed by a shared pointer … does not have ownership of the object Copyright © 2017, 2013, 2007 Pearson Education, Inc.
    [Show full text]
  • Metaclasses: Generative C++
    Metaclasses: Generative C++ Document Number: P0707 R3 Date: 2018-02-11 Reply-to: Herb Sutter ([email protected]) Audience: SG7, EWG Contents 1 Overview .............................................................................................................................................................2 2 Language: Metaclasses .......................................................................................................................................7 3 Library: Example metaclasses .......................................................................................................................... 18 4 Applying metaclasses: Qt moc and C++/WinRT .............................................................................................. 35 5 Alternatives for sourcedefinition transform syntax .................................................................................... 41 6 Alternatives for applying the transform .......................................................................................................... 43 7 FAQs ................................................................................................................................................................. 46 8 Revision history ............................................................................................................................................... 51 Major changes in R3: Switched to function-style declaration syntax per SG7 direction in Albuquerque (old: $class M new: constexpr void M(meta::type target,
    [Show full text]
  • Transparent Garbage Collection for C++
    Document Number: WG21/N1833=05-0093 Date: 2005-06-24 Reply to: Hans-J. Boehm [email protected] 1501 Page Mill Rd., MS 1138 Palo Alto CA 94304 USA Transparent Garbage Collection for C++ Hans Boehm Michael Spertus Abstract A number of possible approaches to automatic memory management in C++ have been considered over the years. Here we propose the re- consideration of an approach that relies on partially conservative garbage collection. Its principal advantage is that objects referenced by ordinary pointers may be garbage-collected. Unlike other approaches, this makes it possible to garbage-collect ob- jects allocated and manipulated by most legacy libraries. This makes it much easier to convert existing code to a garbage-collected environment. It also means that it can be used, for example, to “repair” legacy code with deficient memory management. The approach taken here is similar to that taken by Bjarne Strous- trup’s much earlier proposal (N0932=96-0114). Based on prior discussion on the core reflector, this version does insist that implementations make an attempt at garbage collection if so requested by the application. How- ever, since there is no real notion of space usage in the standard, there is no way to make this a substantive requirement. An implementation that “garbage collects” by deallocating all collectable memory at process exit will remain conforming, though it is likely to be unsatisfactory for some uses. 1 Introduction A number of different mechanisms for adding automatic memory reclamation (garbage collection) to C++ have been considered: 1. Smart-pointer-based approaches which recycle objects no longer ref- erenced via special library-defined replacement pointer types.
    [Show full text]
  • Smart Pointer Demo Goals Time
    Outline Smart Pointer Demo Goals Time CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 13 March 3, 2016 CPSC 427, Lecture 13 1/17 Outline Smart Pointer Demo Goals Time Smart Pointer Demo More on Course Goals Clocks and Time Measurement CPSC 427, Lecture 13 2/17 Outline Smart Pointer Demo Goals Time Smart Pointer Demo CPSC 427, Lecture 13 3/17 Outline Smart Pointer Demo Goals Time Dangling pointers Pointers can be used to permit object sharing from different contexts. One can have a single object of some type T with many pointers in different contexts that all point to that object. CPSC 427, Lecture 13 4/17 Outline Smart Pointer Demo Goals Time Problems with shared objects If the different contexts have different lifetimes, the problem is to know when it is safe to delete the object. It can be difficult to know when an object should be deleted. Failure to delete an object will cause memory leaks. If the object is deleted while there are still points pointing to it, then those pointers become invalid. We call these dangling pointers. Failure to delete or premature deletion of objects are common sources of errors in C++. CPSC 427, Lecture 13 5/17 Outline Smart Pointer Demo Goals Time Avoiding dangling pointers There are several ways to avoid dangling pointers. 1. Have a top-level manager whose lifetime exceeds that of all of the pointers take responsibility for deleting the objects. 2. Use a garbage collection. (This is java's approach.) 3. Use reference counts. That is, keep track somehow of the number of outstanding pointers to an object.
    [Show full text]
  • C++/CLI Tutorial
    CC++++//CCLLII TTuuttoorriiaall Author: Adam Sawicki, [email protected], www.asawicki.info Version 1.0, December 2011 Table of Contents Table of Contents .............................................................................................................................................................. 1 Introduction ...................................................................................................................................................................... 2 What is C++/CLI? ............................................................................................................................................................... 2 Why Use C++/CLI? ......................................................................................................................................................... 2 What C++/CLI is Not? .................................................................................................................................................... 2 Hello World Example ........................................................................................................................................................ 3 Project Properties ............................................................................................................................................................. 3 Namespaces .....................................................................................................................................................................
    [Show full text]
  • These Aren't the COM Objects You're Looking For
    These Aren't the COM Objects You're Looking For November, 2018 Victor Ciura Technical Lead, Advanced Installer www.advancedinstaller.com Abstract Windows COM is 25 years old. Yet it is relevant today more than ever, because Microsoft has bet its entire modern WinRT API on it (starting with Windows 8/10). But, if you’re familiar with the “old” COM with its idioms and SDK helper classes, you’re in for a treat. With the advent of modern C++ 17, using COM objects and new Windows APIs in your applications feels like a completely new experience. In this session, we’ll explore how using modern C++ features can radically transform the shape of your COM code. By eliminating a lot of boilerplate, your code will be much more readable and maintainable. Classic COM idioms around activation and QueryInterface() can feel totally different with modern C++ helpers. A beautiful example of modern COM usage is C++/WinRT (now part of Windows SDK). This is a standard C++ language projection for the new Windows Runtime API. COM memory management, data marshalling, string handling can all feel quite mechanical in nature and very error prone, so a little help from modern C++ facilities would be more than welcomed. Error handling and debugging can be cumbersome for COM like APIs; we’ll explore some tricks to improve this experience, as well. 2018 Victor Ciura | @ciura_victor !X These Aren't the COM Objects You're Looking For ⚙ Part 1 of N 2018 Victor Ciura | @ciura_victor !2 Why COM ? Why are we talking about this ? Have we really exhausted all the cool C++ template<> topics � ? 2018 Victor Ciura | @ciura_victor !3 Who Am I ? Advanced Installer Clang Power Tools @ciura_victor 2018 Victor Ciura | @ciura_victor !4 How many of you have done any COM programming in the last 20 years ? �$ 2018 Victor Ciura | @ciura_victor !5 How many of you are doing COM programming currently (this year) ? #$ 2018 Victor Ciura | @ciura_victor !6 Let's start using COM..
    [Show full text]
  • Thinking in C++ Volume 2 Annotated Solution Guide, Available for a Small Fee From
    1 z 516 Note: This document requires the installation of the fonts Georgia, Verdana and Andale Mono (code font) for proper viewing. These can be found at: http://sourceforge.net/project/showfiles.php?group_id=34153&release_id=105355 Revision 19—(August 23, 2003) Finished Chapter 11, which is now going through review and copyediting. Modified a number of examples throughout the book so that they will compile with Linux g++ (basically fixing case- sensitive naming issues). Revision 18—(August 2, 2003) Chapter 5 is complete. Chapter 11 is updated and is near completion. Updated the front matter and index entries. Home stretch now. Revision 17—(July 8, 2003) Chapters 5 and 11 are 90% done! Revision 16—(June 25, 2003) Chapter 5 text is almost complete, but enough is added to justify a separate posting. The example programs for Chapter 11 are also fairly complete. Added a matrix multiplication example to the valarray material in chapter 7. Chapter 7 has been tech-edited. Many corrections due to comments from users have been integrated into the text (thanks!). Revision 15—(March 1 ,2003) Fixed an omission in C10:CuriousSingleton.cpp. Chapters 9 and 10 have been tech-edited. Revision 14—(January ,2003) Fixed a number of fuzzy explanations in response to reader feedback (thanks!). Chapter 9 has been copy-edited. Revision 13—(December 31, 2002) Updated the exercises for Chapter 7. Finished rewriting Chapter 9. Added a template variation of Singleton to chapter 10. Updated the build directives. Fixed lots of stuff. Chapters 5 and 11 still await rewrite. Revision 12—(December 23, 2002) Added material on Design Patterns as Chapter 10 (Concurrency will move to Chapter 11).
    [Show full text]
  • Phonetic Classification Using Controlled Random Walks
    Phonetic Classification Using Controlled Random Walks Katrin Kirchhoff Andrei Alexandrescuy Department of Electrical Engineering Facebook University of Washington, Seattle, WA, USA [email protected] [email protected] Abstract a given node. When building a graph representing a speech Recently, semi-supervised learning algorithms for phonetic database, the neighbourhood sizes and entropies often exhibit classifiers have been proposed that have obtained promising re- large variance, due to the uneven distribution of phonetic classes sults. Often, these algorithms attempt to satisfy learning criteria (e.g. vowels are more frequent than laterals). MAD offers a that are not inherent in the standard generative or discriminative unified framework for accommodating such effects without the training procedures for phonetic classifiers. Graph-based learn- need for downsampling or upsampling the training data. In the ers in particular utilize an objective function that not only max- past, MAD has been applied to class-instance extraction from imizes the classification accuracy on a labeled set but also the text [10] but it has to our knowledge not been applied to speech global smoothness of the predicted label assignment. In this pa- classification tasks before. In this paper we contrast MAD to per we investigate a novel graph-based semi-supervised learn- the most widely used graph-based learning algorithm, viz. label ing framework that implements a controlled random walk where propagation. different possible moves in the random walk are controlled by probabilities that are dependent on the properties of the graph 2. Graph-Based Learning itself. Experimental results on the TIMIT corpus are presented In graph-based learning, the training and test data are jointly that demonstrate the effectiveness of this procedure.
    [Show full text]
  • Basics Smart Pointer Basics……………………………………………………………………………...1 Which Smart Pointer to Use?
    Basics Smart pointer basics……………………………………………………………………………...1 Which smart pointer to use?.......…………………………………………………………….6 Medium How to implement the pimpl idiom by using unique_ptr………………………12 ​ ​ How to Transfer unique_ptrs From a Set to Another Set……………………….18 ​ ​ Advanced Custom deleters……………………….………………….………………….…………………...25 Changes of deleter during the life of a unique_ptr………………….………………..35 How to return a smart pointer and use covariance………………….………………..38 Smart pointer basics One thing that can rapidly clutter your C++ code and hinder its readability is memory management. Done badly, this can turn a simple logic into an inexpressive slalom of mess management, and make the code lose control over memory safety. The programming task of ensuring that all objects are correctly deleted is very low in terms of levels of abstraction, and since writing good code essentially comes down to respecting levels of abstraction, you want to keep those tasks away from your business logic (or any sort of logic for that matter). Smart pointers are made to deal with this effectively and relieve your code from the dirty work. This series of posts will show you how to take advantage of them to make your code both more ​ expressive and more correct. ​ We're going to go deep into the subject and since I want everyone to be able to follow all of ​ this series, there is no prerequisite and we start off here with the basics of smart pointers. The stack and the heap Like many other languages, C++ has several types of memories, that correspond to different parts of the physical memory. They are: the static, the stack, and the heap.
    [Show full text]
  • Application Development Guide (CLI)
    Ascend 310 Application Development Guide (CLI) Issue 01 Date 2020-05-30 HUAWEI TECHNOLOGIES CO., LTD. Copyright © Huawei Technologies Co., Ltd. 2020. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any means without prior written consent of Huawei Technologies Co., Ltd. Trademarks and Permissions and other Huawei trademarks are trademarks of Huawei Technologies Co., Ltd. All other trademarks and trade names mentioned in this document are the property of their respective holders. Notice The purchased products, services and features are stipulated by the contract made between Huawei and the customer. All or part of the products, services and features described in this document may not be within the purchase scope or the usage scope. Unless otherwise specified in the contract, all statements, information, and recommendations in this document are provided "AS IS" without warranties, guarantees or representations of any kind, either express or implied. The information in this document is subject to change without notice. Every effort has been made in the preparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute a warranty of any kind, express or implied. Issue 01 (2020-05-30) Copyright © Huawei Technologies Co., Ltd. i Ascend 310 Application Development Guide (CLI) Contents Contents 1 Introduction.............................................................................................................................
    [Show full text]
  • Iterators Must Go
    Iterators Must Go Andrei Alexandrescu c 2009 Andrei Alexandrescu 1/52 This Talk • The STL • Iterators • Range-based design • Conclusions c 2009 Andrei Alexandrescu 2/52 What is the STL? c 2009 Andrei Alexandrescu 3/52 Yeah, what is the STL? • A good library of algorithms and data structures. c 2009 Andrei Alexandrescu 4/52 Yeah, what is the STL? • A ( good|bad) library of algorithms and data structures. c 2009 Andrei Alexandrescu 4/52 Yeah, what is the STL? • A ( good|bad|ugly) library of algorithms and data structures. c 2009 Andrei Alexandrescu 4/52 Yeah, what is the STL? • A ( good|bad|ugly) library of algorithms and data structures. • iterators = gcd(containers, algorithms); c 2009 Andrei Alexandrescu 4/52 Yeah, what is the STL? • A ( good|bad|ugly) library of algorithms and data structures. • iterators = gcd(containers, algorithms); • Scrumptious Template Lore • Snout to Tail Length c 2009 Andrei Alexandrescu 4/52 What the STL is • More than the answer, the question is important in the STL • “What would the most general implementations of fundamental containers and algorithms look like?” • Everything else is aftermath • Most importantly: STL is one answer, not the answer c 2009 Andrei Alexandrescu 5/52 STL is nonintuitive c 2009 Andrei Alexandrescu 6/52 STL is nonintuitive • Same way the theory of relativity is nonintuitive • Same way complex numbers are nonintuitive (see e.g. xkcd.com) c 2009 Andrei Alexandrescu 6/52 Nonintuitive • “I want to design the most general algorithms.” • “Sure. What you obviously need is something called iterators. Five of ’em, to be precise.” c 2009 Andrei Alexandrescu 7/52 Nonintuitive • “I want to design the most general algorithms.” • “Sure.
    [Show full text]
  • Copyrighted Material 23 Chapter 2: Data, Variables, and Calculations 25
    CONTENTS INTRODUCTION xxxv CHAPTER 1: PROGRAMMING WITH VISUAL C++ 1 Learning with Visual C++ 1 Writing C++ Applications 2 Learning Desktop Applications Programming 3 Learning C++ 3 Console Applications 4 Windows Programming Concepts 4 What Is the Integrated Development Environment? 5 The Editor 6 The Compiler 6 The Linker 6 The Libraries 6 Using the IDE 7 Toolbar Options 8 Dockable Toolbars 9 Documentation 10 Projects and Solutions 10 Defi ning a Project 10 Debug and Release Versions of Your Program 15 Executing the Program 16 Dealing with Errors 18 Setting Options in Visual C++ 19 Creating and Executing Windows Applications 20 Creating an MFC Application 20 Building and Executing the MFC Application 22 Summary COPYRIGHTED MATERIAL 23 CHAPTER 2: DATA, VARIABLES, AND CALCULATIONS 25 The Structure of a C++ Program 26 Program Comments 31 The #include Directive — Header Files 32 Namespaces and the Using Declaration 33 The main() Function 34 Program Statements 34 fftoc.inddtoc.indd xxviivii 224/08/124/08/12 88:01:01 AAMM CONTENTS Whitespace 37 Statement Blocks 37 Automatically Generated Console Programs 37 Precompiled Header Files 38 Main Function Names 39 Defi ning Variables 39 Naming Variables 39 Keywords in C++ 40 Declaring Variables 41 Initial Values for Variables 41 Fundamental Data Types 42 Integer Variables 42 Character Data Types 44 Integer Type Modifi ers 45 The Boolean Type 46 Floating-Point Types 47 Fundamental Types in C++ 47 Literals 48 Defi ning Synonyms for Data Types 49 Basic Input/Output Operations 50 Input from the Keyboard 50
    [Show full text]