/
Author: Stroustrup B.
Tags: programming languages programming computer science c++ programming language
Year: 2013
Text
ptg10564057
ptg10564057 The C++ Programming Language Fourth Edition Bjarne Stroustrup Upper Saddle River, NJ • Boston • Indianapolis • San Francisco New York • Totonto • Montreal • London • Munich • Paris • Madrid Capetown • Sydney • Tokyo • Singapore • Mexico City
ptg10564057 Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals. The author and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein. The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales, which may include electronic versions and/or custom covers and content particular to your business, training goals, marketing focus, and branding interests. For more information, please contact: U.S . Corporate and Government Sales (800) 382-3419 corpsales@pearsontechgroup.com For sales outside the United States, please contact: International Sales international@pearsoned.com Visit us on the Web: informit.com/aw Library of Congress Cataloging-in-Publication Data Stroustrup, Bjarne. The C++ programming language / Bjarne Stroustrup.— Fourth edition. pages cm Includes bibliographical references and index. ISBN 978-0 -321 -56384-2 (pbk. : alk. paper)—ISBN 0-321-56384-0 (pbk. : alk. paper) 1. C++ (Computer programming language) I. Title. QA76.73 .C153 S77 2013 005.13’3—dc23 2013002159 Copyright © 2013 by Pearson Education, Inc. All rights reserved. Printed in the United States of America. This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. To obtain permission to use material from this work, please submit a written request to Pearson Education, Inc., Permissions Department, One Lake Street, Upper Saddle River, New Jersey 07458, or you may fax your request to (201) 236-3290. This book was typeset in Times and Helvetica by the author. ISBN-13: 978-0 -321 -56384-2 ISBN-10: 0-321 -56384-0 Text printed in the United States on recycled paper at Edwards Brothers Malloy in Ann Arbor, Michigan. Second printing, June 2013
ptg10564057 Contents Contents iii Preface v Preface to the Fourth Edition ...................................................... v Preface to the Third Edition ........................................................ ix Preface to the Second Edition ..................................................... xi Preface to the First Edition ......................................................... xii Part I: Introductory Material 1. Notes to the Reader ..................................................................... 3 2. A Tour of C++: The Basics ......................................................... 37 3. A Tour of C++: Abstraction Mechanisms ................................... 59 4. A Tour of C++: Containers and Algorithms ............................... 87 5. A Tour of C++: Concurrency and Utilities ................................. 111 Part II: Basic Facilities 133 6. Types and Declarations ............................................................... 135 7. Pointers, Arrays, and References ................................................ 171 8. Structures, Unions, and Enumerations ........................................ 201 9. Statements ................................................................................... 225 10. Expressions ................................................................................. 241
ptg10564057 iv Contents 11. Select Operations ........................................................................ 273 12. Functions ..................................................................................... 305 13. Exception Handling .................................................................... 343 14. Namespaces ................................................................................. 389 15. Source Files and Programs .......................................................... 419 Part III: Abstraction Mechanisms 447 16. Classes ........................................................................................ 449 17. Construction, Cleanup, Copy, and Move .................................... 481 18. Overloading ................................................................................. 527 19. Special Operators ........................................................................ 549 20. Derived Classes ........................................................................... 577 21. Class Hierarchies ........................................................................ 613 22. Run-Time Type Information ....................................................... 641 23. Templates .................................................................................... 665 24. Generic Programming ................................................................. 699 25. Specialization .............................................................................. 721 26. Instantiation ................................................................................ 741 27. Templates and Hierarchies .......................................................... 759 28. Metaprogramming ....................................................................... 779 29. A Matrix Design ......................................................................... 827 Part IV: The Standard Library 857 30. Standard Library Summary ......................................................... 859 31. STL Containers ........................................................................... 885 32. STL Algorithms .......................................................................... 927 33. STL Iterators ............................................................................... 953 34. Memory and Resources ............................................................... 973 35. Utilities ........................................................................................ 1009 36. Strings ......................................................................................... 1033 37. Regular Expressions .................................................................... 1051 38. I/O Streams ................................................................................. 1073 39. Locales ........................................................................................ 1109 40. Numerics ..................................................................................... 1159 41. Concurrency ................................................................................ 1191 42. Threads and Tasks ....................................................................... 1209 43. The C Standard Library .............................................................. 1253 44. Compatibility .............................................................................. 1267 Index 1281
ptg10564057 Preface All problems in computer science can be solved by another level of indirection, except for the problem of too many layers of indirection. – David J. Wheeler C++ feels like a new language. That is, I can express my ideas more clearly, more simply, and more directly in C++11 than I could in C++98. Furthermore, the resulting programs are better checked by the compiler and run faster. In this book, I aim for completeness. I describe every language feature and standard-library component that a professional programmer is likely to need. For each, I provide: • Rationale: What kinds of problems is it designed to help solve? What principles underlie the design? What are the fundamental limitations? • Specification: What is its definition? The level of detail is chosen for the expert program- mer; the aspiring language lawyer can follow the many references to the ISO standard. • Examples: How can it be used well by itself and in combination with other features? What are the key techniques and idioms? What are the implications for maintainability and per- formance? The use of C++ has changed dramatically over the years and so has the language itself. From the point of view of a programmer, most of the changes have been improvements. The current ISO standard C++ (ISO/IEC 14882-2011, usually called C++11) is simply a far better tool for writing quality software than were previous versions. How is it a better tool? What kinds of programming styles and techniques does modern C++ support? What language and standard-library features sup- port those techniques? What are the basic building blocks of elegant, correct, maintainable, and efficient C++ code? Those are the key questions answered by this book. Many answers are not the same as you would find with 1985, 1995, or 2005 vintage C++: progress happens. C++ is a general-purpose programming language emphasizing the design and use of type-rich, lightweight abstractions. It is particularly suited for resource-constrained applications, such as those found in software infrastructures. C++ rewards the programmer who takes the time to master
ptg10564057 vi Preface techniques for writing quality code. C++ is a language for someone who takes the task of program- ming seriously. Our civilization depends critically on software; it had better be quality software. There are billions of lines of C++ deployed. This puts a premium on stability, so 1985 and 1995 C++ code still works and will continue to work for decades. However, for all applications, you can do better with modern C++; if you stick to older styles, you will be writing lower-quality and worse-performing code. The emphasis on stability also implies that standards-conforming code you write today will still work a couple of decades from now. All code in this book conforms to the 2011 ISO C++ standard. This book is aimed at three audiences: • C++ programmers who want to know what the latest ISO C++ standard has to offer, • C programmers who wonder what C++ provides beyond C, and • People with a background in application languages, such as Java, C#, Python, and Ruby, looking for something ‘‘closer to the machine’’ – something more flexible, something offer- ing better compile-time checking, or something offering better performance. Naturally, these three groups are not disjoint – a professional software developer masters more than just one programming language. This book assumes that its readers are programmers. If you ask, ‘‘What’s a for-loop?’’ or ‘‘What’s a compiler?’’ then this book is not (yet) for you; instead, I recommend my Programming: Principles and Practice Using C++ to get started with programming and C++. Furthermore, I assume that readers have some maturity as software developers. If you ask ‘‘Why bother testing?’’ or say, ‘‘All languages are basically the same; just show me the syntax’’ or are confident that there is a single language that is ideal for every task, this is not the book for you. What features does C++11 offer over and above C++98? A machine model suitable for modern computers with lots of concurrency. Language and standard-library facilities for doing systems- level concurrent programming (e.g ., using multicores). Regular expression handling, resource management pointers, random numbers, improved containers (including, hash tables), and more. General and uniform initialization, a simpler for-statement, move semantics, basic Unicode support, lambdas, general constant expressions, control over class defaults, variadic templates, user-defined literals, and more. Please remember that those libraries and language features exist to support pro- gramming techniques for developing quality software. They are meant to be used in combination – as bricks in a building set – rather than to be used individually in relative isolation to solve a spe- cific problem. A computer is a universal machine, and C++ serves it in that capacity. In particular, C++’s design aims to be sufficiently flexible and general to cope with future problems undreamed of by its designers.
ptg10564057 vii Acknowledgments In addition to the people mentioned in the acknowledgment sections of the previous editions, I would like to thank Pete Becker, Hans-J. Boehm, Marshall Clow, Jonathan Coe, Lawrence Crowl, Walter Daugherty, J. Daniel Garcia, Robert Harle, Greg Hickman, Howard Hinnant, Brian Kernighan, Daniel Krügler, Nevin Liber, Michel Michaud, Gary Powell, Jan Christiaan van Winkel, and Leor Zolman. Without their help this book would have been much poorer. Thanks to Howard Hinnant for answering many questions about the standard library. Andrew Sutton is the author of the Origin library, which was the testbed for much of the discus- sion of emulating concepts in the template chapters, and of the matrix library that is the topic of Chapter 29. The Origin library is open source and can be found by searching the Web for ‘‘Origin’’ and ‘‘Andrew Sutton.’’ Thanks to my graduate design class for finding more problems with the ‘‘tour chapters’’ than anyone else. Had I been able to follow every piece of advice of my reviewers, the book would undoubtedly have been much improved, but it would also have been hundreds of pages longer. Every expert reviewer suggested adding technical details, advanced examples, and many useful development conventions; every novice reviewer (or educator) suggested adding examples; and most reviewers observed (correctly) that the book may be too long. Thanks to Princeton University’s Computer Science Department, and especially Prof. Brian Kernighan, for hosting me for part of the sabbatical that gave me time to write this book. Thanks to Cambridge University’s Computer Lab, and especially Prof. Andy Hopper, for host- ing me for part of the sabbatical that gave me time to write this book. Thanks to my editor, Peter Gordon, and his production team at Addison-Wesley for their help and patience. College Station, Texas Bjarne Stroustrup
ptg10564057 This page intentionally left blank
ptg10564057 Preface to the Third Edition Programming is understanding. – Kristen Nygaard I find using C++ more enjoyable than ever. C++’s support for design and programming has improved dramatically over the years, and lots of new helpful techniques have been developed for its use. However, C++ is not just fun. Ordinary practical programmers have achieved significant improvements in productivity, maintainability, flexibility, and quality in projects of just about any kind and scale. By now, C++ has fulfilled most of the hopes I originally had for it, and also suc- ceeded at tasks I hadn’t even dreamt of. This book introduces standard C++† and the key programming and design techniques supported by C++. Standard C++ is a far more powerful and polished language than the version of C++ intro- duced by the first edition of this book. New language features such as namespaces, exceptions, templates, and run-time type identification allow many techniques to be applied more directly than was possible before, and the standard library allows the programmer to start from a much higher level than the bare language. About a third of the information in the second edition of this book came from the first. This third edition is the result of a rewrite of even larger magnitude. It offers something to even the most experienced C++ programmer; at the same time, this book is easier for the novice to approach than its predecessors were. The explosion of C++ use and the massive amount of experience accumu- lated as a result makes this possible. The definition of an extensive standard library makes a difference to the way C++ concepts can be presented. As before, this book presents C++ independently of any particular implementation, and as before, the tutorial chapters present language constructs and concepts in a ‘‘bottom up’’ order so that a construct is used only after it has been defined. However, it is much easier to use a well-designed library than it is to understand the details of its implementation. Therefore, the stan- dard library can be used to provide realistic and interesting examples well before a reader can be assumed to understand its inner workings. The standard library itself is also a fertile source of pro- gramming examples and design techniques. This book presents every major C++ language feature and the standard library. It is organized around language and library facilities. However, features are presented in the context of their use. † ISO/IEC 14882, Standard for the C++ Programming Language.
ptg10564057 x Preface to the Third Edition That is, the focus is on the language as the tool for design and programming rather than on the lan- guage in itself. This book demonstrates key techniques that make C++ effective and teaches the fundamental concepts necessary for mastery. Except where illustrating technicalities, examples are taken from the domain of systems software. A companion, The Annotated C++ Language Stan- dard, presents the complete language definition together with annotations to make it more compre- hensible. The primary aim of this book is to help the reader understand how the facilities offered by C++ support key programming techniques. The aim is to take the reader far beyond the point where he or she gets code running primarily by copying examples and emulating programming styles from other languages. Only a good understanding of the ideas behind the language facilities leads to mastery. Supplemented by implementation documentation, the information provided is sufficient for completing significant real-world projects. The hope is that this book will help the reader gain new insights and become a better programmer and designer. Acknowledgments In addition to the people mentioned in the acknowledgement sections of the first and second edi- tions, I would like to thank Matt Austern, Hans Boehm, Don Caldwell, Lawrence Crowl, Alan Feuer, Andrew Forrest, David Gay, Tim Griffin, Peter Juhl, Brian Kernighan, Andrew Koenig, Mike Mowbray, Rob Murray, Lee Nackman, Joseph Newcomer, Alex Stepanov, David Vandevoorde, Peter Weinberger, and Chris Van Wyk for commenting on draft chapters of this third edition. With- out their help and suggestions, this book would have been harder to understand, contained more errors, been slightly less complete, and probably been a little bit shorter. I would also like to thank the volunteers on the C++ standards committees who did an immense amount of constructive work to make C++ what it is today. It is slightly unfair to single out indi- viduals, but it would be even more unfair not to mention anyone, so I’d like to especially mention Mike Ball, Dag Br ̈uck, Sean Corfield, Ted Goldstein, Kim Knuttila, Andrew Koenig, Dmitry Lenkov, Nathan Myers, Martin O’Riordan, Tom Plum, Jonathan Shopiro, John Spicer, Jerry Schwarz, Alex Stepanov, and Mike Vilot, as people who each directly cooperated with me over some part of C++ and its standard library. After the initial printing of this book, many dozens of people have mailed me corrections and suggestions for improvements. I have been able to accommodate many of their suggestions within the framework of the book so that later printings benefitted significantly. Translators of this book into many languages have also provided many clarifications. In response to requests from readers, I have added appendices D and E. Let me take this opportunity to thank a few of those who helped: Dave Abrahams, Matt Austern, Jan Bielawski, Janina Mincer Daszkiewicz, Andrew Koenig, Diet- mar K ̈uhl, Nicolai Josuttis, Nathan Myers, Paul E. Sevin ̧c, Andy Tenne-Sens, Shoichi Uchida, Ping-Fai (Mike) Yang, and Dennis Yelle. Murray Hill, New Jersey Bjarne Stroustrup
ptg10564057 Preface to the Second Edition The road goes ever on and on. – Bilbo Baggins As promised in the first edition of this book, C++ has been evolving to meet the needs of its users. This evolution has been guided by the experience of users of widely varying backgrounds working in a great range of application areas. The C++ user-community has grown a hundredfold during the six years since the first edition of this book; many lessons have been learned, and many techniques have been discovered and/or validated by experience. Some of these experiences are reflected here. The primary aim of the language extensions made in the last six years has been to enhance C++ as a language for data abstraction and object-oriented programming in general and to enhance it as a tool for writing high-quality libraries of user-defined types in particular. A ‘‘high-quality library,’’ is a library that provides a concept to a user in the form of one or more classes that are convenient, safe, and efficient to use. In this context, safe means that a class provides a specific type-safe interface between the users of the library and its providers; efficient means that use of the class does not impose significant overheads in run-time or space on the user compared with hand- written C code. This book presents the complete C++ language. Chapters 1 through 10 give a tutorial introduc- tion; Chapters 11 through 13 provide a discussion of design and software development issues; and, finally, the complete C++ reference manual is included. Naturally, the features added and resolu- tions made since the original edition are integral parts of the presentation. They include refined overloading resolution, memory management facilities, and access control mechanisms, type-safe linkage, const and static member functions, abstract classes, multiple inheritance, templates, and exception handling. C++ is a general-purpose programming language; its core application domain is systems pro- gramming in the broadest sense. In addition, C++ is successfully used in many application areas that are not covered by this label. Implementations of C++ exist from some of the most modest microcomputers to the largest supercomputers and for almost all operating systems. Consequently, this book describes the C++ language itself without trying to explain a particular implementation, programming environment, or library. This book presents many examples of classes that, though useful, should be classified as ‘‘toys.’’ This style of exposition allows general principles and useful techniques to stand out more clearly than they would in a fully elaborated program, where they would be buried in details. Most
ptg10564057 xii Preface to the Second Edition of the useful classes presented here, such as linked lists, arrays, character strings, matrices, graphics classes, associative arrays, etc., are available in ‘‘bulletproof ’’ and/or ‘‘goldplated’’ versions from a wide variety of commercial and non-commercial sources. Many of these ‘‘industrial strength’’ classes and libraries are actually direct and indirect descendants of the toy versions found here. This edition provides a greater emphasis on tutorial aspects than did the first edition of this book. However, the presentation is still aimed squarely at experienced programmers and endeavors not to insult their intelligence or experience. The discussion of design issues has been greatly expanded to reflect the demand for information beyond the description of language features and their immediate use. Technical detail and precision have also been increased. The reference man- ual, in particular, represents many years of work in this direction. The intent has been to provide a book with a depth sufficient to make more than one reading rewarding to most programmers. In other words, this book presents the C++ language, its fundamental principles, and the key tech- niques needed to apply it. Enjoy! Acknowledgments In addition to the people mentioned in the acknowledgements section in the preface to the first edi- tion, I would like to thank Al Aho, Steve Buroff, Jim Coplien, Ted Goldstein, Tony Hansen, Lor- raine Juhl, Peter Juhl, Brian Kernighan, Andrew Koenig, Bill Leggett, Warren Montgomery, Mike Mowbray, Rob Murray, Jonathan Shopiro, Mike Vilot, and Peter Weinberger for commenting on draft chapters of this second edition. Many people influenced the development of C++ from 1985 to 1991. I can mention only a few: Andrew Koenig, Brian Kernighan, Doug McIlroy, and Jonathan Shopiro. Also thanks to the many participants of the ‘‘external reviews’’ of the reference manual drafts and to the people who suffered through the first year of X3J16. Murray Hill, New Jersey Bjarne Stroustrup
ptg10564057 Preface to the First Edition Language shapes the way we think, and determines what we can think about. – B.L.Whorf C++ is a general purpose programming language designed to make programming more enjoyable for the serious programmer. Except for minor details, C++ is a superset of the C programming lan- guage. In addition to the facilities provided by C, C++ provides flexible and efficient facilities for defining new types. A programmer can partition an application into manageable pieces by defining new types that closely match the concepts of the application. This technique for program construc- tion is often called data abstraction. Objects of some user-defined types contain type information. Such objects can be used conveniently and safely in contexts in which their type cannot be deter- mined at compile time. Programs using objects of such types are often called object based. When used well, these techniques result in shorter, easier to understand, and easier to maintain programs. The key concept in C++ is class. A class is a user-defined type. Classes provide data hiding, guaranteed initialization of data, implicit type conversion for user-defined types, dynamic typing, user-controlled memory management, and mechanisms for overloading operators. C++ provides much better facilities for type checking and for expressing modularity than C does. It also contains improvements that are not directly related to classes, including symbolic constants, inline substitu- tion of functions, default function arguments, overloaded function names, free store management operators, and a reference type. C++ retains C’s ability to deal efficiently with the fundamental objects of the hardware (bits, bytes, words, addresses, etc.) . This allows the user-defined types to be implemented with a pleasing degree of efficiency. C++ and its standard libraries are designed for portability. The current implementation will run on most systems that support C. C libraries can be used from a C++ program, and most tools that support programming in C can be used with C++. This book is primarily intended to help serious programmers learn the language and use it for nontrivial projects. It provides a complete description of C++, many complete examples, and many more program fragments.
ptg10564057 xiv Preface to the First Edition Acknowledgments C++ could never have matured without the constant use, suggestions, and constructive criticism of many friends and colleagues. In particular, Tom Cargill, Jim Coplien, Stu Feldman, Sandy Fraser, Steve Johnson, Brian Kernighan, Bart Locanthi, Doug McIlroy, Dennis Ritchie, Larry Rosler, Jerry Schwarz, and Jon Shopiro provided important ideas for development of the language. Dave Pre- sotto wrote the current implementation of the stream I/O library. In addition, hundreds of people contributed to the development of C++ and its compiler by sending me suggestions for improvements, descriptions of problems they had encountered, and compiler errors. I can mention only a few: Gary Bishop, Andrew Hume, Tom Karzes, Victor Milenkovic, Rob Murray, Leonie Rose, Brian Schmult, and Gary Walker. Many people have also helped with the production of this book, in particular, Jon Bentley, Laura Eaves, Brian Kernighan, Ted Kowalski, Steve Mahaney, Jon Shopiro, and the participants in the C++ course held at Bell Labs, Columbus, Ohio, June 26-27, 1985. Murray Hill, New Jersey Bjarne Stroustrup
ptg10564057 Part I Introduction This introduction gives an overview of the major concepts and features of the C++ pro- gramming language and its standard library. It also provides an overview of this book and explains the approach taken to the description of the language facilities and their use. In addition, the introductory chapters present some background information about C++, the design of C++, and the use of C++. Chapters 1 Notes to the Reader 2 A Tour of C++: The Basics 3 A Tour of C++: Abstraction Mechanisms 4 A Tour of C++: Containers and Algorithms 5 A Tour of C++: Concurrency and Utilities
ptg10564057 2 Introduction Part I ‘‘... and you, Marcus, you have given me many things; now I shall give you this good advice. Be many people. Give up the game of being always Marcus Cocoza. You have worried too much about Marcus Cocoza, so that you have been really his slave and prisoner. You have not done anything without first considering how it would affect Marcus Cocoza’s happiness and prestige. You were always much afraid that Marcus might do a stupid thing, or be bored. What would it really have mattered? All over the world people are doing stupid things ... I should like you to be easy, your little heart to be light again. You must from now, be more than one, many people, as many as you can think of ...’’ – Karen Blixen, The Dreamers from Seven Gothic Tales (1934)
ptg10564057 1 Notes to the Reader Hurry Slowly (festina lente). – Octavius, Caesar Augustus • The Structure of This Book Introduction; Basic Facilities; Abstraction Mechanisms; The Standard Library; Examples and References • The Design of C++ Programming Styles; Type Checking; C Compatibility; Language, Libraries, and Systems • Learning C++ Programming in C++; Suggestions for C++ Programmers; Suggestions for C Programmers; Suggestions for Java Programmers • History Timeline; The Early Years; The 1998 Standard; The 2011 Standard; What is C++ Used for? • Advice • References 1.1 The Structure of This Book A pure tutorial sorts its topics so that no concept is used before it has been introduced; it must be read linearly starting with page one. Conversely, a pure reference manual can be accessed starting at any point; it describes each topic succinctly with references (forward and backward) to related topics. A pure tutorial can in principle be read without prerequisites – it carefully describes all. A pure reference can be used only by someone familiar with all fundamental concepts and techniques. This book combines aspects of both. If you know most concepts and techniques, you can access it on a per-chapter or even on a per-section basis. If not, you can start at the beginning, but try not to get bogged down in details. Use the index and the cross-references.
ptg10564057 4 Notes to the Reader Chapter 1 Making parts of the book relatively self-contained implies some repetition, but repetition also serves as review for people reading the book linearly. The book is heavily cross-referenced both to itself and to the ISO C++ standard. Experienced programmers can read the (relatively) quick ‘‘tour’’ of C++ to gain the overview needed to use the book as a reference. This book consists of four parts: Part I Introduction: Chapter 1 (this chapter) is a guide to this book and provides a bit of C++ background. Chapters 2-5 give a quick introduction to the C++ language and its standard library. Part II Basic Facilities: Chapters 6-15 describe C++’s built-in types and the basic facili- ties for constructing programs out of them. Part III Abstraction Mechanisms: Chapters 16-29 describe C++’s abstraction mecha- nisms and their use for object-oriented and generic programming. Part IV Chapters 30-44 provide an overview of the standard library and a discussion of compatibility issues. 1.1.1 Introduction This chapter, Chapter 1, provides an overview of this book, some hints about how to use it, and some background information about C++ and its use. You are encouraged to skim through it, read what appears interesting, and return to it after reading other parts of the book. Please do not feel obliged to read it all carefully before proceeding. The following chapters provide an overview of the major concepts and features of the C++ pro- gramming language and its standard library: Chapter 2 A Tour of C++: The Basics describes C++’s model of memory, computation, and error handling. Chapter 3 A Tour of C++: Abstraction Mechanisms presents the language features support- ing data abstraction, object-oriented programming, and generic programming. Chapter 4 A Tour of C++: Containers and Algorithms introduces strings, simple I/O, con- tainers, and algorithms as provided by the standard library. Chapter 5 A Tour of C++: Concurrency and Utilities outlines the standard-library utilities related to resource management, concurrency, mathematical computation, regu- lar expressions, and more. This whirlwind tour of C++’s facilities aims to give the reader a taste of what C++ offers. In partic- ular, it should convince readers that C++ has come a long way since the first, second, and third edi- tions of this book. 1.1.2 Basic Facilities Part II focuses on the subset of C++ that supports the styles of programming traditionally done in C and similar languages. It introduces the notions of type, object, scope, and storage. It presents the fundamentals of computation: expressions, statements, and functions. Modularity – as supported by namespaces, source files, and exception handling – is also discussed: Chapter 6 Types and Declarations: Fundamental types, naming, scopes, initialization, sim- ple type deduction, object lifetimes, and type aliases
ptg10564057 Section 1.1 .2 Basic Facilities 5 Chapter 7 Pointers, Arrays, and References Chapter 8 Structures, Unions, and Enumerations Chapter 9 Statements: Declarations as statements, selection statements (if and switch), itera- tion statements (for, while, and do), goto, and comments Chapter 10 Expressions: A desk calculator example, survey of operators, constant expres- sions, and implicit type conversion. Chapter 11 Select Operations: Logical operators, the conditional expression, increment and decrement, free store (new and delete), {}-lists, lambda expressions, and explicit type conversion (static_cast and const_cast) Chapter 12 Functions: Function declarations and definitions, inline functions, constexpr functions, argument passing, overloaded functions, pre- and postconditions, pointers to functions, and macros Chapter 13 Exception Handling: Styles of error handling, exception guarantees, resource management, enforcing invariants, throw and catch,avector implementation Chapter 14 Namespaces: namespace, modularization and interface, composition using name- spaces Chapter 15 Source Files and Programs: Separate compilation, linkage, using header files, and program start and termination I assume that you are familiar with most of the programming concepts used in Part I. For example, I explain the C++ facilities for expressing recursion and iteration, but I do not go into technical details or spend much time explaining how these concepts are useful. The exception to this rule is exceptions. Many programmers lack experience with exceptions or got their experience from languages (such as Java) where resource management and exception han- dling are not integrated. Consequently, the chapter on exception handling (Chapter 13) presents the basic philosophy of C++ exception handling and resource management. It goes into some detail about strategy with a focus on the ‘‘Resource Acquisition Is Initialization’’ technique (RAII). 1.1.3 Abstraction Mechanisms Part III describes the C++ facilities supporting various forms of abstraction, including object-ori- ented and generic programming. The chapters fall into three rough categories: classes, class hierar- chies, and templates. The first four chapters concentrate of the classes themselves: Chapter 16 Classes: The notion of a user-defined type, a class, is the foundation of all C++ abstraction mechanisms. Chapter 17 Construction, Cleanup, Copy, and Move shows how a programmer can define the meaning of creation and initialization of objects of a class. Further, the meaning of copy, move, and destruction can be specified. Chapter 18 Operator Overloading presents the rules for giving meaning to operators for user-defined types with an emphasis on conventional arithmetic and logical oper- ators, such as +, ∗, and &. Chapter 19 Special Operators discusses the use of user-defined operator for non-arithmetic purposes, such as [] for subscripting, () for function objects, and −> for ‘‘smart pointers.’’
ptg10564057 6 Notes to the Reader Chapter 1 Classes can be organized into hierarchies: Chapter 20 Derived Classes presents the basic language facilities for building hierarchies out of classes and the fundamental ways of using them. We can provide complete separation between an interface (an abstract class) and its implementations (derived classes); the connection between them is provided by virtual functions. The C++ model for access control (public, protected, and private) is presented. Chapter 21 Class Hierarchies discusses ways of using class hierarchies effectively. It also presents the notion of multiple inheritance, that is, a class having more than one direct base class. Chapter 22 Run-Time Type Information presents ways to navigate class hierarchies using data stored in objects. We can use dynamic_cast to inquire whether an object of a base class was defined as an object of a derived class and use the typeid to gain minimal information from an object (such as the name of its class). Many of the most flexible, efficient, and useful abstractions involve the parameterization of types (classes) and algorithms (functions) with other types and algorithms: Chapter 23 Templates presents the basic principles behind templates and their use. Class templates, function templates, and template aliases are presented. Chapter 24 Generic Programming introduces the basic techniques for designing generic pro- grams. The technique of lifting an abstract algorithm from a number of concrete code examples is central, as is the notion of concepts specifying a generic algo- rithm’s requirements on its arguments. Chapter 25 Specialization describes how templates are used to generate classes and func- tions, specializations, given a set of template arguments. Chapter 26 Instantiation focuses on the rules for name binding. Chapter 27 Templates and Hierarchies explains how templates and class hierarchies can be used in combination. Chapter 28 Metaprogramming explores how templates can be used to generate programs. Templates provide a Turing-complete mechanism for generating code. Chapter 29 A Matrix Design gives a longish example to show how language features can be used in combination to solve a complex design problem: the design of an N- dimensional matrix with near-arbitrary element types. The language features supporting abstraction techniques are described in the context of those tech- niques. The presentation technique in Part III differs from that of Part II in that I don’t assume that the reader knows the techniques described. 1.1.4 The Standard Library The library chapters are less tutorial than the language chapters. In particular, they are meant to be read in any order and can be used as a user-level manual for the library components: Chapter 30 Standard-Library Overview gives an overview of the standard library, lists the standard-library headers, and presents language support and diagnostics support, such as exception and system_error. Chapter 31 STL Containers presents the containers from the iterators, containers, and algo- rithms framework (called the STL), including vector, map, and unordered_set.
ptg10564057 Section 1.1 .4 The Standard Library 7 Chapter 32 STL Algorithms presents the algorithms from the STL, including find(), sort(), and merge(). Chapter 33 STL Iterators presents iterators and other utilities from the STL, including reverse_iterator, move_iterator, and function. Chapter 34 Memory and Resources presents utility components related to memory and resource management, such as array, bitset, pair, tuple, unique_ptr, shared_ptr, allocators, and the garbage collector interface. Chapter 35 Utilities presents minor utility components, such as time utilities, type traits, and various type functions. Chapter 36 Strings documents the string library, including the character traits that are the basis for the use of different character sets. Chapter 37 Regular Expressions describes the regular expression syntax and the various ways of using it for string matching, including regex_match() for matching a complete string, regex_search() for finding a pattern in a string, regex_replace() for simple replacement, and regex_iterator for general traversal of a stream of characters. Chapter 38 I/O Streams documents the stream I/O library. It describes formatted and unfor- matted input and output, error handling, and buffering. Chapter 39 Locales describes class locale and its various facets that provide support for the handling of cultural differences in character sets, formatting of numeric values, formatting of date and time, and more. Chapter 40 Numerics describes facilities for numerical computation (such as complex, valarray, random numbers, and generalized numerical algorithms). Chapter 41 Concurrency presents the C++ basic memory model and the facilities offered for concurrent programming without locks. Chapter 42 Threads and Tasks presents the classes providing threads-and-locks-style concur- rent programming (such as thread, timed_mutex, lock_guard, and try_lock()) and the support for task-based concurrency (such as future and async()). Chapter 43 The C Standard Library documents the C standard library (including printf() and clock()) as incorporated into the C++ standard library. Chapter 44 Compatibility discusses the relation between C and C++ and between Standard C++ (also called ISO C++) and the versions of C++ that preceded it. 1.1.5 Examples and References This book emphasizes program organization rather than the design of algorithms. Consequently, I avoid clever or harder-to-understand algorithms. A trivial algorithm is typically better suited to illustrate an aspect of the language definition or a point about program structure. For example, I use a Shell sort where, in real code, a quicksort would be better. Often, reimplementation with a more suitable algorithm is an exercise. In real code, a call of a library function is typically more appropriate than the code used here to illustrate language features. Textbook examples necessarily give a warped view of software development. By clarifying and simplifying the examples, the complexities that arise from scale disappear. I see no substitute for writing realistically sized programs in order to get an impression of what programming and a
ptg10564057 8 Notes to the Reader Chapter 1 programming language are really like. This book concentrates on the language features and the standard-library facilities. These are the basic techniques from which every program is composed. The rules and techniques for such composition are emphasized. The selection of examples reflects my background in compilers, foundation libraries, and simu- lations. The emphasis reflects my interest in systems programming. Examples are simplified ver- sions of what is found in real code. The simplification is necessary to keep programming language and design points from getting lost in details. My ideal is the shortest and clearest example that illustrates a design principle, a programming technique, a language construct, or a library feature. There are no ‘‘cute’’ examples without counterparts in real code. For purely language-technical examples, I use variables named x and y, types called A and B, and functions called f() and g(). Where possible, the C++ language and library features are presented in the context of their use rather than in the dry manner of a manual. The language features presented and the detail in which they are described roughly reflect my view of what is needed for effective use of C++. The purpose is to give you an idea of how a feature can be used, often in combination with other features. An understanding of every language-technical detail of a language feature or library component is nei- ther necessary nor sufficient for writing good programs. In fact, an obsession with understanding every little detail is a prescription for awful – overelaborate and overly clever – code. What is needed is an understanding of design and programming techniques together with an appreciation of application domains. I assume that you have access to online information sources. The final arbiter of language and standard-library rules is the ISO C++ standard [C++,2011]. References to parts of this book are of the form §2.3 .4 (Chapter 2, section 3, subsection 4) and §iso.5 .3 .1 (ISO C++ standard, §5.3 .1). Italics are used sparingly for emphasis (e.g ., ‘‘a string literal is not acceptable’’), for first occurrences of important concepts (e.g ., polymorphism), and for com- ments in code examples. To save a few trees and to simplify additions, the hundreds of exercises for this book have been moved to the Web. Look for them at www.stroustrup.com . The language and library used in this book are ‘‘pure C++’’ as defined by the C++ standard [C++,2011]. Therefore, the examples should run on every up-to-date C++ implementation. The major program fragments in this book were tried using several C++ implementations. Examples using features only recently adopted into C++ didn’t compile on every implementation. However, I see no point in mentioning which implementations failed to compile which examples. Such infor- mation would soon be out of date because implementers are working hard to ensure that their implementations correctly accept every C++ feature. See Chapter 44 for suggestions on how to cope with older C++ compilers and with code written for C compilers. I use C++11 features freely wherever I find them most appropriate. For example, I prefer {}-style initializers and using for type aliases. In places, that usage may startle ‘‘old timers.’’ How- ever, being startled is often a good way to start reviewing material. On the other hand, I don’t use new features just because they are new; my ideal is the most elegant expression of the fundamental ideas – and that may very well be using something that has been in C++ or even in C for ages. Obviously, if you have to use a pre-C++11 compiler (say, because some of your customers have not yet upgraded to the current standard), you have to refrain from using novel features. However, please don’t assume that ‘‘the old ways’’ are better or simpler just because they are old and familiar. §44.2 summarizes the differences between C++98 and C++11.
ptg10564057 Section 1.2 The Design of C++ 9 1.2 The Design of C++ The purpose of a programming language is to help express ideas in code. In that, a programming language performs two related tasks: it provides a vehicle for the programmer to specify actions to be executed by the machine, and it provides a set of concepts for the programmer to use when thinking about what can be done. The first purpose ideally requires a language that is ‘‘close to the machine’’ so that all important aspects of a machine are handled simply and efficiently in a way that is reasonably obvious to the programmer. The C language was primarily designed with this in mind. The second purpose ideally requires a language that is ‘‘close to the problem to be solved’’ so that the concepts of a solution can be expressed directly and concisely. The facilities added to C to create C++, such as function argument checking, const, classes, constructors and destructors, exceptions, and templates, were primarily designed with this in mind. Thus, C++ is based on the idea of providing both • direct mappings of built-in operations and types to hardware to provide efficient memory use and efficient low-level operations, and • affordable and flexible abstraction mechanisms to provide user-defined types with the same notational support, range of uses, and performance as built-in types. This was initially achieved by applying ideas from Simula to C. Over the years, further application of these simple ideals resulted in a far more general, efficient, and flexible set of facilities. The result supports a synthesis of programming styles that can be simultaneously efficient and elegant. The design of C++ has focused on programming techniques dealing with fundamental notions such as memory, mutability, abstraction, resource management, expression of algorithms, error han- dling, and modularity. Those are the most important concerns of a systems programmer and more generally of programmers of resource-constrained and high-performance systems. By defining libraries of classes, class hierarchies, and templates, you can write C++ programs at a much higher level than the one presented in this book. For example, C++ is widely used in finan- cial systems, for game development, and for scientific computation (§1.4 .5). For high-level appli- cations programming to be effective and convenient, we need libraries. Using just the bare lan- guage features makes almost all programming quite painful. That’s true for every general-purpose language. Conversely, given suitable libraries just about any programming task can be pleasant. My standard introduction of C++ used to start: • C++ is a general-purpose programming language with a bias toward systems programming. This is still true. What has changed over the years is an increase in the importance, power, and flexibility of C++’s abstraction mechanisms: • C++ is a general-purpose programming language providing a direct and efficient model of hardware combined with facilities for defining lightweight abstractions. Or terser: • C++ is a language for developing and using elegant and efficient abstractions. By general-purpose programming language I mean a language designed to support a wide variety of uses. C++ has indeed been used for an incredible variety of uses (from microcontrollers to huge distributed commercial applications), but the key point is that C++ is not deliberately specialized for any given application area. No language is ideal for every application and every programmer, but the ideal for C++ is to support the widest possible range of application areas well.
ptg10564057 10 Notes to the Reader Chapter 1 By systems programming I mean writing code that directly uses hardware resources, has serious resource constraints, or closely interacts with code that does. In particular, the implementation of software infrastructure (e.g ., device drivers, communications stacks, virtual machines, operating systems, operations systems, programming environments, and foundation libraries) is mostly sys- tems programming. The importance of the ‘‘bias toward systems programming’’ qualification in my long-standing characterization of C++ is that C++ has not been simplified (compromised) by ejecting the facilities aimed at the expert-level use of hardware and systems resources in the hope of making it more suitable for other application areas. Of course, you can also program in ways that completely hide hardware, use expensive abstrac- tions (e.g ., every object on the free store and every operation a virtual function), use inelegant styles (e.g., overabstraction), or use essentially no abstractions (‘‘glorified assembly code’’). However, many languages can do that, so those are not distinguishing characteristics of C++. The Design and Evolution of C++ book [Stroustrup,1994] (known as D&E) outlines the ideas and design aims of C++ in greater detail, but two principles should be noted: • Leave no room for a lower-level language below C++ (except for assembly code in rare cases). If you can write more efficient code in a lower-level language then that language will most likely become the systems programming language of choice. • What you don’t use you don’t pay for. If programmers can hand-write reasonable code to simulate a language feature or a fundamental abstraction and provide even slightly better performance, someone will do so, and many will imitate. Therefore, a language feature and a fundamental abstraction must be designed not to waste a single byte or a single processor cycle compared to equivalent alternatives. This is known as the zero-overhead principle. These are Draconian principles, but essential in some (but obviously not all) contexts. In particular, the zero-overhead principle repeatedly led C++ to simpler, more elegant, and more powerful facili- ties than were first envisioned. The STL is an example (§4.1 .1, §4.4, §4.5, Chapter 31, Chapter 32, Chapter 33). These principles have been essential in the effort to raise the level of programming. 1.2.1 Programming Style Languages features exist to provide support for programming styles. Please don’t look at an indi- vidual language feature as a solution, but as one building brick from a varied set which can be com- bined to express solutions. The general ideals for design and programming can be expressed simply: • Express ideas directly in code. • Express independent ideas independently in code. • Represent relationships among ideas directly in code. • Combine ideas expressed in code freely – where and only where combinations make sense. • Express simple ideas simply. These are ideals shared by many people, but languages designed to support them can differ dramat- ically. A fundamental reason for that is that a language embodies a set of engineering tradeoffs reflecting differing needs, tastes, and histories of various individuals and communities. C++’s answers to the general design challenges were shaped by its origins in systems programming (going back to C and BCPL [Richards,1980]), its aim to address issues of program complexity through abstraction (going back to Simula), and its history.
ptg10564057 Section 1.2 .1 Programming Style 11 The C++ language features most directly support four programming styles: • Procedural programming • Data abstraction • Object-oriented programming • Generic programming However, the emphasis is on the support of effective combinations of those. The best (most main- tainable, most readable, smallest, fastest, etc.) solution to most nontrivial problems tends to be one that combines aspects of these styles. As is usual with important terms in the computing world, a wide variety of definitions of these terms are popular in various parts of the computing industry and academia. For example, what I refer to as a ‘‘programming style,’’ others call a ‘‘programming technique’’ or a ‘‘paradigm.’’ I pre- fer to use ‘‘programming technique’’ for something more limited and language-specific. I feel uncomfortable with the word ‘‘paradigm’’ as pretentious and (from Kuhn’s original definition) hav- ing implied claims of exclusivity. My ideal is language facilities that can be used elegantly in combination to support a continuum of programming styles and a wide variety of programming techniques. • Procedural programming: This is programming focused on processing and the design of suitable data structures. It is what C was designed to support (and Algol, and Fortran, as well as many other languages). C++’s support comes in the form of the built-in types, oper- ators, statements, functions, structs, unions, etc. With minor exceptions, C is a subset of C++. Compared to C, C++ provides further support for procedural programming in the form of many additional language constructs and a stricter, more flexible, and more support- ive type system. • Data abstraction: This is programming focused on the design of interfaces, hiding imple- mentation details in general and representations in particular. C++ supports concrete and abstract classes. The facilities for defining classes with private implementation details, con- structors and destructors, and associated operations directly support this. The notion of an abstract class provides direct support for complete data hiding. • Object-oriented programming: This is programming focused on the design, implementation, and use of class hierarchies. In addition to allowing the definition lattices of classes, C++ provides a variety of features for navigating class lattices and for simplifying the definition of a class out of existing ones. Class hierarchies provide run-time polymorphism (§20.3 .2, §21.2) and encapsulation (§20.4, §20.5). • Generic programming: This is programming focused on the design, implementation, and use of general algorithms. Here, ‘‘general’’ means that an algorithm can be designed to accept a wide variety of types as long as they meet the algorithm’s requirements on its arguments. The template is C++’s main support for generic programming. Templates provide (compile- time) parametric polymorphism. Just about anything that increases the flexibility or efficiency of classes improves the support of all of those styles. Thus, C++ could be (and has been) called class oriented. Each of these styles of design and programming has contributed to the synthesis that is C++. Focusing exclusively on one of these styles is a mistake: except for toy examples, doing so leads to wasted development effort and suboptimal (inflexible, verbose, poorly performing, unmaintainable, etc.) code.
ptg10564057 12 Notes to the Reader Chapter 1 I wince when someone characterizes C++ exclusively through one of these styles (e.g., ‘‘C++ is an object-oriented language’’) or uses a term (e.g ., ‘‘hybrid’’ or ‘‘mixed paradigm’’) to imply that a more restrictive language would be preferable. The former misses the fact that all the styles men- tioned have contributed something significant to the synthesis; the latter denies the validity of the synthesis. The styles mentioned are not distinct alternatives: each contributes techniques to a more expressive and effective style of programming, and C++ provides direct language support for their use in combination. From its inception, the design of C++ aimed at a synthesis of programming and design styles. Even the earliest published account of C++ [Stroustrup,1982] presents examples that use these dif- ferent styles in combination and presents language features aimed at supporting such combinations: • Classes support all of the mentioned styles; all rely on the user representing ideas as user- defined types or objects of user-defined types. • Public/private access control supports data abstraction and object-oriented programming by making a clear distinction between interface and implementation. • Member functions, constructors, destructors, and user-defined assignment provide a clean functional interface to objects as needed by data abstraction and object-oriented program- ming. They also provide a uniform notation as needed for generic programming. More general overloading had to wait until 1984 and uniform initialization until 2010. • Function declarations provide specific statically checked interfaces to member functions as well as freestanding functions, so they support all of the mentioned styles. They are neces- sary for overloading. At the time, C lacked ‘‘function prototypes’’ but Simula had function declarations as well as member functions. • Generic functions and parameterized types (generated from functions and classes using macros) support generic programming. Templates had to wait until 1988. • Base and derived classes provide the foundation for object-oriented programming and some forms of data abstraction. Virtual functions had to wait until 1983. • Inlining made the use of these facilities affordable in systems programming and for building run-time and space efficient libraries. These early features are general abstraction mechanisms, rather than support for disjoint program- ming styles. Today’s C++ provides much better support for design and programming based on lightweight abstraction, but the aim of elegant and efficient code was there from the very beginning. The developments since 1981 provide much better support for the synthesis of the programming styles (‘‘paradigms’’) originally considered and significantly improve their integration. The fundamental object in C++ has identity; that is, it is located in a specific location in mem- ory and can be distinguished from other objects with (potentially) the same value by comparing addresses. Expressions denoting such objects are called lvalues (§6.4). However, even from the earliest days of C++’s ancestors [Barron,1963] there have also been objects without identity (objects for which an address cannot be safely stored for later use). In C++11, this notion of rvalue has been developed into a notion of a value that can be moved around cheaply (§3.3 .2, §6.4 .1, §7.7 .2). Such objects are the basis of techniques that resemble what is found in functional pro- gramming (where the notion of objects with identity is viewed with horror). This nicely comple- ments the techniques and language features (e.g ., lambda expressions) developed primarily for generic programming. It also solves classical problems related to ‘‘simple abstract data types,’’ such as how to elegantly and efficiently return a large matrix from an operation (e.g., a matrix +).
ptg10564057 Section 1.2 .1 Programming Style 13 From the very earliest days, C++ programs and the design of C++ itself have been concerned about resource management. The ideal was (and is) for resource management to be • simple (for implementers and especially for users), • general (a resource is anything that has to be acquired from somewhere and later released), • efficient (obey the zero-overhead principle; §1.2), • perfect (no leaks are acceptable), and • statically type-safe. Many important C++ classes, such as the standard library’s vector, string, thread, mutex, unique_ptr, fstream, and regex, are resource handles. Foundation and application libraries beyond the standard provided many more examples, such as Matrix and Widget. The initial step in supporting the notion of resource handles was taken with the provision of constructors and destructors in the very first ‘‘C with Classes’’ draft. This was soon backed with the ability to control copy by defining assignment as well as copy constructors. The introduction of move constructors and move assign- ments (§3.3) in C++11 completes this line of thinking by allowing cheap movement of potentially large objects from scope to scope (§3.3 .2) and to simply control the lifetime of polymorphic or shared objects (§5.2 .1). The facilities supporting resource management also benefit abstractions that are not resource handles. Any class that establishes and maintains an invariant relies on a subset of those features. 1.2.2 Type Checking The connection between the language in which we think/program and the problems and solutions we can imagine is very close. For this reason, restricting language features with the intent of elimi- nating programmer errors is, at best, dangerous. A language provides a programmer with a set of conceptual tools; if these are inadequate for a task, they will be ignored. Good design and the absence of errors cannot be guaranteed merely by the presence or absence of specific language fea- tures. However, the language features and the type system are provided for the programmer to pre- cisely and concisely represent a design in code. The notion of static types and compile-time type checking is central to effective use of C++. The use of static types is key to expressiveness, maintainability, and performance. Following Sim- ula, the design of user-defined types with interfaces that are checked at compile time is key to the expressiveness of C++. The C++ type system is extensible in nontrivial ways (Chapter 3, Chapter 16, Chapter 18, Chapter 19, Chapter 21, Chapter 23, Chapter 28, Chapter 29), aiming for equal sup- port for built-in types and user-defined types. C++ type-checking and data-hiding features rely on compile-time analysis of programs to pre- vent accidental corruption of data. They do not provide secrecy or protection against someone who is deliberately breaking the rules: C++ protects against accident, not against fraud. They can, how- ever, be used freely without incurring run-time or space overheads. The idea is that to be useful, a language feature must not only be elegant, it must also be affordable in the context of a real-world program. C++’s static type system is flexible, and the use of simple user-defined types implies little, if any overhead. The aim is to support a style of programming that represents distinct ideas as dis- tinct types, rather than just using generalizations, such as integer, floating-point number, string, ‘‘raw memory,’’ and ‘‘object,’’ everywhere. A type-rich style of programming makes code more
ptg10564057 14 Notes to the Reader Chapter 1 readable, maintainable, and analyzable. A trivial type system allows only trivial analysis, whereas a type-rich style of programming opens opportunities for nontrivial error detection and optimiza- tion. C++ compilers and development tools support such type-based analysis [Stroustrup,2012]. Maintaining most of C as a subset and preserving the direct mapping to hardware needed for the most demanding low-level systems programming tasks implies the ability to break the static type system. However, my ideal is (and always was) complete type safety. In this, I agree with Dennis Ritchie, who said, ‘‘C is a strongly typed, weakly checked language.’’ Note that Simula was both type-safe and flexible. In fact, my ideal when I started on C++ was ‘‘Algol68 with Classes’’ rather than ‘‘C with Classes.’’ However, the list of solid reasons against basing my work on type-safe Algol68 [Woodward,1974] was long and painful. So, perfect type safety is an ideal that C++ as a language can only approximate. But it is an ideal that C++ programmers (especially library builders) can strive for. Over the years, the set of language features, standard-library components, and techniques supporting that ideal has grown. Outside of low-level sections of code (hopefully isolated by type-safe interfaces), code that interfaces to code obeying different language conven- tions (e.g ., an operating system call interface), and the implementations of fundamental abstractions (e.g., string and vector), there is now little need for type-unsafe code. 1.2.3 C Compatibility C++ was developed from the C programming language and, with few exceptions, retains C as a subset. The main reasons for relying on C were to build on a proven set of low-level language facilities and to be part of a technical community. Great importance was attached to retaining a high degree of compatibility with C [Koenig,1989] [Stroustrup,1994] (Chapter 44); this (unfortu- nately) precluded cleaning up the C syntax. The continuing, more or less parallel evolution of C and C++ has been a constant source of concern and requires constant attention [Stroustrup,2002]. Having two committees devoted to keeping two widely used languages ‘‘as compatible as possible’’ is not a particularly good way of organizing work. In particular, there are differences in opinion as to the value of compatibility, differences in opinion on what constitutes good programming, and differences in opinion on what support is needed for good programming. Just keeping up commu- nication between the committees is a large amount of work. One hundred percent C/C++ compatibility was never a goal for C++ because that would com- promise type safety and the smooth integration of user-defined and built-in types. However, the definition of C++ has been repeatedly reviewed to remove gratuitous incompatibilities; C++ is now more compatible with C than it was originally. C++98 adopted many details from C89 (§44.3 .1). When C then evolved from C89 [C,1990] to C99 [C,1999], C++ adopted almost all of the new fea- tures, leaving out VLAs (variable-length arrays) as a misfeature and designated initializers as redundant. C’s facilities for low-level systems programming tasks are retained and enhanced; for example, see inlining (§3.2 .1 .1, §12.1 .5, §16.2 .8) and constexpr (§2.2 .3, §10.4, §12.1 .6). Conversely, modern C has adopted (with varying degrees of faithfulness and effectiveness) many features from C++ (e.g ., const, function prototypes, and inlining; see [Stroustrup,2002]). The definition of C++ has been revised to ensure that a construct that is both legal C and legal C++ has the same meaning in both languages (§44.3). One of the original aims for C was to replace assembly coding for the most demanding systems programming tasks. When C++ was designed, care was taken not to compromise the gains in this
ptg10564057 Section 1.2 .3 C Compatibility 15 area. The difference between C and C++ is primarily in the degree of emphasis on types and struc- ture. C is expressive and permissive. Through extensive use of the type system, C++ is even more expressive without loss of performance. Knowing C is not a prerequisite for learning C++. Programming in C encourages many tech- niques and tricks that are rendered unnecessary by C++ language features. For example, explicit type conversion (casting) is less frequently needed in C++ than it is in C (§1.3.3). However, good C programs tend to be C++ programs. For example, every program in Kernighan and Ritchie, The C Programming Language, Second Edition [Kernighan,1988], is a C++ program. Experience with any statically typed language will be a help when learning C++. 1.2.4 Language, Libraries, and Systems The C++ fundamental (built-in) types, operators, and statements are those that computer hardware deals with directly: numbers, characters, and addresses. C++ has no built-in high-level data types and no high-level primitive operations. For example, the C++ language does not provide a matrix type with an inversion operator or a string type with a concatenation operator. If a user wants such a type, it can be defined in the language itself. In fact, defining a new general-purpose or applica- tion-specific type is the most fundamental programming activity in C++. A well-designed user- defined type differs from a built-in type only in the way it is defined, not in the way it is used. The C++ standard library (Chapter 4, Chapter 5, Chapter 30, Chapter 31, etc.) provides many examples of such types and their uses. From a user’s point of view, there is little difference between a built-in type and a type provided by the standard library. Except for a few unfortunate and unimportant his- torical accidents, the C++ standard library is written in C++. Writing the C++ standard library in C++ is a crucial test of the C++ type system and abstraction mechanisms: they must be (and are) sufficiently powerful (expressive) and efficient (affordable) for the most demanding systems pro- gramming tasks. This ensures that they can be used in large systems that typically consist of layer upon layer of abstraction. Features that would incur run-time or memory overhead even when not used were avoided. For example, constructs that would make it necessary to store ‘‘housekeeping information’’ in every object were rejected, so if a user declares a structure consisting of two 16-bit quantities, that struc- ture will fit into a 32-bit register. Except for the new, delete, typeid, dynamic_cast, and throw opera- tors, and the try-block, individual C++ expressions and statements need no run-time support. This can be essential for embedded and high-performance applications. In particular, this implies that the C++ abstraction mechanisms are usable for embedded, high-performance, high-reliability, and real-time applications. So, programmers of such applications don’t have to work with a low-level (error-prone, impoverished, and unproductive) set of language features. C++ was designed to be used in a traditional compilation and run-time environment: the C pro- gramming environment on the UNIX system [UNIX,1985]. Fortunately, C++ was never restricted to UNIX; it simply used UNIX and C as a model for the relationships among language, libraries, compilers, linkers, execution environments, etc. That minimal model helped C++ to be successful on essentially every computing platform. There are, however, good reasons for using C++ in envi- ronments that provide significantly more run-time support. Facilities such as dynamic loading, incremental compilation, and a database of type definitions can be put to good use without affecting the language.
ptg10564057 16 Notes to the Reader Chapter 1 Not every piece of code can be well structured, hardware-independent, easy to read, etc. C++ possesses features that are intended for manipulating hardware facilities in a direct and efficient way without concerns for safety or ease of comprehension. It also possesses facilities for hiding such code behind elegant and safe interfaces. Naturally, the use of C++ for larger programs leads to the use of C++ by groups of program- mers. C++’s emphasis on modularity, strongly typed interfaces, and flexibility pays off here. How- ever, as programs get larger, the problems associated with their development and maintenance shift from being language problems to being more global problems of tools and management. This book emphasizes techniques for providing general-purpose facilities, generally useful types, libraries, etc. These techniques will serve programmers of small programs as well as pro- grammers of large ones. Furthermore, because all nontrivial programs consist of many semi-inde- pendent parts, the techniques for writing such parts serve programmers of all applications. I use the implementation and use of standard-library components, such as vector, as examples. This introduces library components and their underlying design concepts and implementation tech- niques. Such examples show how programmers might design and implement their own libraries. However, if the standard library provides a component that addresses a problem, it is almost always better to use that component than to build your own. Even if the standard component is arguably slightly inferior to a home-built component for a particular problem, the standard component is likely to be more widely applicable, more widely available, and more widely known. Over the longer term, the standard component (possibly accessed through a convenient custom interface) is likely to lower long-term maintenance, porting, tuning, and education costs. You might suspect that specifying a program by using a more detailed type structure would increase the size of the program source text (or even the size of the generated code). With C++, this is not so. A C++ program declaring function argument types, using classes, etc., is typically a bit shorter than the equivalent C program not using these facilities. Where libraries are used, a C++ program will appear much shorter than its C equivalent, assuming, of course, that a functioning C equivalent could have been built. C++ supports systems programming. This implies that C++ code is able to effectively interop- erate with software written in other languages on a system. The idea of writing all software in a single language is a fantasy. From the beginning, C++ was designed to interoperate simply and efficiently with C, assembler, and Fortran. By that, I meant that a C++, C, assembler, or Fortran function could call functions in the other languages without extra overhead or conversion of data structures passed among them. C++ was designed to operate within a single address space. The use of multiple processes and multiple address spaces relied on (extralinguistic) operating system support. In particular, I assumed that a C++ programmer would have the operating systems command language available for composing processes into a system. Initially, I relied on the UNIX Shell for that, but just about any ‘‘scripting language’’ will do. Thus, C++ provided no support for multiple address spaces and no support for multiple processes, but it was used for systems relying on those features from the earliest days. C++ was designed to be part of large, concurrent, multilanguage systems.
ptg10564057 Section 1.3 Learning C++ 17 1.3 Learning C++ No programming language is perfect. Fortunately, a programming language does not have to be perfect to be a good tool for building great systems. In fact, a general-purpose programming lan- guage cannot be perfect for all of the many tasks to which it is put. What is perfect for one task is often seriously flawed for another because perfection in one area implies specialization. Thus, C++ was designed to be a good tool for building a wide variety of systems and to allow a wide variety of ideas to be expressed directly. Not everything can be expressed directly using the built-in features of a language. In fact, that isn’t even the ideal. Language features exist to support a variety of programming styles and tech- niques. Consequently, the task of learning a language should focus on mastering the native and nat- ural styles for that language – not on understanding of every little detail of every language feature. Writing programs is essential; understanding a programming language is not just an intellectual exercise. Practical application of ideas is necessary. In practical programming, there is little advantage in knowing the most obscure language fea- tures or using the largest number of features. A single language feature in isolation is of little inter- est. Only in the context provided by techniques and by other features does the feature acquire meaning and interest. Thus, when reading the following chapters, please remember that the real purpose of examining the details of C++ is to be able to use language features and library facilities in concert to support good programming styles in the context of sound designs. No significant system is built exclusively in terms of the language features themselves. We build and use libraries to simplify the task of programming and to increase the quality of our sys- tems. We use libraries to improve maintainability, portability, and performance. Fundamental application concepts are represented as abstractions (e.g ., classes, templates, and class hierarchies) in libraries. Many of the most fundamental programming concepts are represented in the standard library. Thus, learning the standard library is an integral part of learning C++. The standard library is the repository of much hard-earned knowledge of how to use C++ well. C++ is widely used for teaching and research. This has surprised some who – correctly – point out that C++ isn’t the smallest or cleanest language ever designed. It is, however: • Sufficiently clean for successfully teaching basic design and programming concepts • Sufficiently comprehensive to be a vehicle for teaching advanced concepts and techniques • Sufficiently realistic, efficient, and flexible for demanding projects • Sufficiently commercial to be a vehicle for putting what is learned into nonacademic use • Sufficiently available for organizations and collaborations relying on diverse development and execution environments C++ is a language that you can grow with. The most important thing to do when learning C++ is to focus on fundamental concepts (such as type safety, resource management, and invariants) and programming techniques (such as resource management using scoped objects and the use of iterators in algorithms) and not get lost in language-technical details. The purpose of learning a programming language is to become a better programmer, that is, to become more effective at designing and implementing new systems and at maintaining old ones. For this, an appreciation of programming and design techniques is far more important than understanding all the details. The understanding of technical details comes with time and practice.
ptg10564057 18 Notes to the Reader Chapter 1 C++ programming is based on strong static type checking, and most techniques aim at achiev- ing a high level of abstraction and a direct representation of the programmer’s ideas. This can usu- ally be done without compromising run-time and space efficiency compared to lower-level tech- niques. To gain the benefits of C++, programmers coming to it from a different language must learn and internalize idiomatic C++ programming style and technique. The same applies to pro- grammers used to earlier and less expressive versions of C++. Thoughtlessly applying techniques effective in one language to another typically leads to awk- ward, poorly performing, and hard-to-maintain code. Such code is also most frustrating to write because every line of code and every compiler error message reminds the programmer that the lan- guage used differs from ‘‘the old language.’’ You can write in the style of Fortran, C, Lisp, Java, etc., in any language, but doing so is neither pleasant nor economical in a language with a different philosophy. Every language can be a fertile source of ideas about how to write C++ programs. However, ideas must be transformed into something that fits with the general structure and type system of C++ in order to be effective in C++. Over the basic type system of a language, only Pyrrhic victories are possible. In the continuing debate on whether one needs to learn C before C++, I am firmly convinced that it is best to go directly to C++. C++ is safer and more expressive, and it reduces the need to focus on low-level techniques. It is easier for you to learn the trickier parts of C that are needed to compensate for its lack of higher-level facilities after you have been exposed to the common subset of C and C++ and to some of the higher-level techniques supported directly in C++. Chapter 44 is a guide for programmers going from C++ to C, say, to deal with legacy code. My opinion on how to teach C++ to novices is represented by [Stroustrup,2008]. There are several independently developed implementations of C++. They are supported by a wealth of tools, libraries, and software development environments. To help master all of this you can find textbooks, manuals, and a bewildering variety of online resources. If you plan to use C++ seriously, I strongly suggest that you obtain access to several such sources. Each has its own emphasis and bias, so use at least two. 1.3.1 Programming in C++ The question ‘‘How does one write good programs in C++?’’ is very similar to the question ‘‘How does one write good English prose?’’ There are two answers: ‘‘Know what you want to say’’ and ‘‘Practice. Imitate good writing.’’ Both appear to be as appropriate for C++ as they are for English – and as hard to follow. The main ideal for C++ programming – as for programming in most higher-level languages – is to express concepts (ideas, notions, etc.) from a design directly in code. We try to ensure that the concepts we talk about, represent with boxes and arrows on our whiteboard, and find in our (non- programming) textbooks have direct and obvious counterparts in our programs: [1] Represent ideas directly in code. [2] Represent relationships among ideas directly in code (e.g ., hierarchical, parametric, and ownership relationships). [3] Represent independent ideas independently in code. [4] Keep simple things simple (without making complex things impossible).
ptg10564057 Section 1.3 .1 Programming in C++ 19 More specifically: [5] Prefer statically type-checked solutions (when applicable). [6] Keep information local (e.g., avoid global variables, minimize the use of pointers). [7] Don’t overabstract (i.e., don’t generalize, introduce class hierarchies, or parameterize beyond obvious needs and experience). More specific suggestions are listed in §1.3 .2 . 1.3.2 Suggestions for C++ Programmers By now, many people have been using C++ for a decade or two. Many more are using C++ in a single environment and have learned to live with the restrictions imposed by early compilers and first-generation libraries. Often, what an experienced C++ programmer has failed to notice over the years is not the introduction of new features as such, but rather the changes in relationships between features that make fundamental new programming techniques feasible. In other words, what you didn’t think of when first learning C++ or found impractical just might be a superior approach today. You find out only by reexamining the basics. Read through the chapters in order. If you already know the contents of a chapter, you can be done in minutes. If you don’t already know the contents, you’ll have learned something unex- pected. I learned a fair bit writing this book, and I suspect that hardly any C++ programmer knows every feature and technique presented. Furthermore, to use the language well, you need a perspec- tive that brings order to the set of features and techniques. Through its organization and examples, this book offers such a perspective. Take the opportunity offered by the new C++11 facilities to modernize your design and pro- gramming techniques: [1] Use constructors to establish invariants (§2.4 .3.2, §13.4, §17.2 .1). [2] Use constructor/destructor pairs to simplify resource management (RAII; §5.2, §13.3). [3] Avoid ‘‘naked’’ new and delete (§3.2.1 .2, §11.2.1). [4] Use containers and algorithms rather than built-in arrays and ad hoc code (§4.4, §4.5, §7.4, Chapter 32). [5] Prefer standard-library facilities to locally developed code (§1.2 .4). [6] Use exceptions, rather than error codes, to report errors that cannot be handled locally (§2.4 .3, §13.1). [7] Use move semantics to avoid copying large objects (§3.3 .2, §17.5 .2). [8] Use unique_ptr to reference objects of polymorphic type (§5.2 .1). [9] Use shared_ptr to reference shared objects, that is, objects without a single owner that is responsible for their destruction (§5.2.1). [10] Use templates to maintain static type safety (eliminate casts) and avoid unnecessary use of class hierarchies (§27.2). It might also be a good idea to review the advice for C and Java programmers (§1.3 .3, §1.3 .4). 1.3.3 Suggestions for C Programmers The better one knows C, the harder it seems to be to avoid writing C++ in C style, thereby losing many of the potential benefits of C++. Please take a look at Chapter 44, which describes the differ- ences between C and C++.
ptg10564057 20 Notes to the Reader Chapter 1 [1] Don’t think of C++ as C with a few features added. C++ can be used that way, but only suboptimally. To get really major advantages from C++ as compared to C, you need to apply different design and implementation styles. [2] Don’t write C in C++; that is often seriously suboptimal for both maintenance and perfor- mance. [3] Use the C++ standard library as a teacher of new techniques and programming styles. Note the difference from the C standard library (e.g ., = rather than strcpy() for copying and == rather than strcmp() for comparing). [4] Macro substitution is almost never necessary in C++. Use const (§7.5), constexpr (§2.2 .3, §10.4), enum or enum class (§8.4) to define manifest constants, inline (§12.1.5) to avoid function-calling overhead, templates (§3.4, Chapter 23) to specify families of functions and types, and namespaces (§2.4 .2, §14.3 .1) to avoid name clashes. [5] Don’t declare a variable before you need it, and initialize it immediately. A declaration can occur anywhere a statement can (§9.3), in for-statement initializers (§9.5), and in con- ditions (§9.4 .3). [6] Don’t use malloc(). The new operator (§11.2) does the same job better, and instead of realloc(), try a vector (§3.4 .2). Don’t just replace malloc() and free() with ‘‘naked’’ new and delete (§3.2 .1 .2, §11.2 .1). [7] Avoid void∗, unions, and casts, except deep within the implementation of some function or class. Their use limits the support you can get from the type system and can harm per- formance. In most cases, a cast is an indication of a design error. If you must use an explicit type conversion, try using one of the named casts (e.g ., static_cast; §11.5 .2) for a more precise statement of what you are trying to do. [8] Minimize the use of arrays and C-style strings. C++ standard-library strings (§4.2), arrays (§8.2 .4), and vectors (§4.4 .1) can often be used to write simpler and more maintainable code compared to the traditional C style. In general, try not to build yourself what has already been provided by the standard library. [9] Avoid pointer arithmetic except in very specialized code (such as a memory manager) and for simple array traversal (e.g ., ++p). [10] Do not assume that something laboriously written in C style (avoiding C++ features such as classes, templates, and exceptions) is more efficient than a shorter alternative (e.g ., using standard-library facilities). Often (but of course not always), the opposite is true. To obey C linkage conventions, a C++ function must be declared to have C linkage (§15.2 .5). 1.3.4 Suggestions for Java Programmers C++ and Java are rather different languages with similar syntaxes. Their aims are significantly dif- ferent and so are many of their application domains. Java is not a direct successor to C++ in the sense of a language that can do the same as its predecessor, but better and also more. To use C++ well, you need to adopt programming and design techniques appropriate to C++, rather than trying to write Java in C++. It is not just an issue of remembering to delete objects that you create with new because you can’t rely on the presence of a garbage collector: [1] Don’t simply mimic Java style in C++; that is often seriously suboptimal for both main- tainability and performance.
ptg10564057 Section 1.3 .4 Suggestions for Java Programmers 21 [2] Use the C++ abstraction mechanisms (e.g ., classes and templates): don’t fall back to a C style of programming out of a false feeling of familiarity. [3] Use the C++ standard library as a teacher of new techniques and programming styles. [4] Don’t immediately invent a unique base for all of your classes (an Object class). Typi- cally, you can do better without it for many/most classes. [5] Minimize the use of reference and pointer variables: use local and member variables (§3.2 .1 .2, §5.2, §16.3 .4, §17.1). [6] Remember: a variable is never implicitly a reference. [7] Think of pointers as C++’s equivalent to Java references (C++ references are more lim- ited; there is no reseating of C++ references). [8] A function is not virtual by default. Not every class is meant for inheritance. [9] Use abstract classes as interfaces to class hierarchies; avoid ‘‘brittle base classes,’’ that is, base classes with data members. [10] Use scoped resource management (‘‘Resource Acquisition Is Initialization’’; RAII) when- ever possible. [11] Use a constructor to establish a class invariant (and throw an exception if it can’t). [12] If a cleanup action is needed when an object is deleted (e.g., goes out of scope), use a de- structor for that. Don’t imitate finally (doing so is more ad hoc and in the longer run far more work than relying on destructors). [13] Avoid ‘‘naked’’ new and delete; instead, use containers (e.g ., vector, string, and map) and handle classes (e.g ., lock and unique_ptr). [14] Use freestanding functions (nonmember functions) to minimize coupling (e.g ., see the standard algorithms), and use namespaces (§2.4 .2, Chapter 14) to limit the scope of free- standing functions. [15] Don’t use exception specifications (except noexcept; §13.5 .1 .1). [16] A C++ nested class does not have access to an object of the enclosing class. [17] C++ offers only the most minimal run-time reflection: dynamic_cast and typeid (Chapter 22). Rely more on compile-time facilities (e.g ., compile-time polymorphism; Chapter 27, Chapter 28). Most of this advice applies equally to C# programmers. 1.4 History I invented C++, wrote its early definitions, and produced its first implementation. I chose and for- mulated the design criteria for C++, designed its major language features, developed or helped to develop many of the early libraries, and was responsible for the processing of extension proposals in the C++ standards committee. C++ was designed to provide Simula’s facilities for program organization [Dahl,1970] [Dahl,1972] together with C’s efficiency and flexibility for systems programming [Kernighan,1978] [Kernighan,1988]. Simula is the initial source of C++’s abstraction mechanisms. The class con- cept (with derived classes and virtual functions) was borrowed from it. However, templates and exceptions came to C++ later with different sources of inspiration.
ptg10564057 22 Notes to the Reader Chapter 1 The evolution of C++ was always in the context of its use. I spent a lot of time listening to users and seeking out the opinions of experienced programmers. In particular, my colleagues at AT&T Bell Laboratories were essential for the growth of C++ during its first decade. This section is a brief overview; it does not try to mention every language feature and library component. Furthermore, it does not go into details. For more information, and in particular for more names of people who contributed, see [Stroustrup,1993], [Stroustrup,2007], and [Strous- trup,1994]. My two papers from the ACM History of Programming Languages conference and my Design and Evolution of C++ book (known as ‘‘D&E’’) describe the design and evolution of C++ in detail and document influences from other programming languages. Most of the documents produced as part of the ISO C++ standards effort are available online [WG21]. In my FAQ, I try to maintain a connection between the standard facilities and the people who proposed and refined those facilities [Stroustrup,2010]. C++ is not the work of a faceless, anonymous committee or of a supposedly omnipotent ‘‘dictator for life’’; it is the work of many dedicated, experienced, hard-working individuals. 1.4.1 Timeline The work that led to C++ started in the fall of 1979 under the name ‘‘C with Classes.’’ Here is a simplified timeline: 1979 Work on ‘‘C with Classes’’ started. The initial feature set included classes and derived classes, public/private access control, constructors and destructors, and function declara- tions with argument checking. The first library supported non-preemptive concurrent tasks and random number generators. 1984 ‘‘C with Classes’’ was renamed to C++. By then, C++ had acquired virtual functions, function and operator overloading, references, and the I/O stream and complex number libraries. 1985 First commercial release of C++ (October 14). The library included I/O streams, com- plex numbers, and tasks (nonpreemptive scheduling). 1985 The C++ Programming Language (‘‘TC++PL,’’ October 14) [Stroustrup,1986]. 1989 The Annotated C++ Reference Manual (‘‘the ARM’’). 1991 The C++ Programming Language, Second Edition [Stroustrup,1991], presenting generic programming using templates and error handling based on exceptions (including the ‘‘Resource Acquisition Is Initialization’’ general resource management idiom). 1997 The C++ Programming Language, Third Edition [Stroustrup,1997] introduced ISO C++, including namespaces, dynamic_cast, and many refinements of templates. The standard library added the STL framework of generic containers and algorithms. 1998 ISO C++ standard. 2002 Work on a revised standard, colloquially named C++0x, started. 2003 A ‘‘bug fix’’ revision of the ISO C++ standard was issued. A C++ Technical Report introduced new standard-library components, such as regular expressions, unordered con- tainers (hash tables), and resource management pointers, which later became part of C++0x. 2006 An ISO C++ Technical Report on Performance was issued to answer questions of cost, predictability, and techniques, mostly related to embedded systems programming.
ptg10564057 Section 1.4 .1 Timeline 23 2009 C++0x was feature complete. It provided uniform initialization, move semantics, vari- adic template arguments, lambda expressions, type aliases, a memory model suitable for concurrency, and much more. The standard library added several components, including threads, locks, and most of the components from the 2003 Technical Report. 2011 ISO C++11 standard was formally approved. 2012 The first complete C++11 implementations emerged. 2012 Work on future ISO C++ standards (referred to as C++14 and C++17) started. 2013 The C++ Programming Language, Fourth Edition introduced C++11. During development, C++11 was known as C++0x. As is not uncommon in large projects, we were overly optimistic about the completion date. 1.4.2 The Early Years I originally designed and implemented the language because I wanted to distribute the services of a UNIX kernel across multiprocessors and local-area networks (what are now known as multicores and clusters). For that, I needed some event-driven simulations for which Simula would have been ideal, except for performance considerations. I also needed to deal directly with hardware and pro- vide high-performance concurrent programming mechanisms for which C would have been ideal, except for its weak support for modularity and type checking. The result of adding Simula-style classes to C, ‘‘C with Classes,’’ was used for major projects in which its facilities for writing pro- grams that use minimal time and space were severely tested. It lacked operator overloading, refer- ences, virtual functions, templates, exceptions, and many, many details [Stroustrup,1982]. The first use of C++ outside a research organization started in July 1983. The name C++ (pronounced ‘‘see plus plus’’) was coined by Rick Mascitti in the summer of 1983 and chosen as the replacement for ‘‘C with Classes’’ by me. The name signifies the evolu- tionary nature of the changes from C; ‘‘++’’ is the C increment operator. The slightly shorter name ‘‘C+’’ is a syntax error; it had also been used as the name of an unrelated language. Connoisseurs of C semantics find C++ inferior to ++C. The language was not called D, because it was an exten- sion of C, because it did not attempt to remedy problems by removing features, and because there already existed several would-be C successors named D. For yet another interpretation of the name C++, see the appendix of [Orwell,1949]. C++ was designed primarily so that my friends and I would not have to program in assembler, C, or various then-fashionable high-level languages. Its main purpose was to make writing good programs easier and more pleasant for the individual programmer. In the early years, there was no C++ paper design; design, documentation, and implementation went on simultaneously. There was no ‘‘C++ project’’ either, or a ‘‘C++ design committee.’’ Throughout, C++ evolved to cope with problems encountered by users and as a result of discussions among my friends, my colleagues, and me. 1.4 .2.1 Language Features and Library Facilities The very first design of C++ (then called ‘‘C with Classes’’) included function declarations with argument type checking and implicit conversions, classes with the public/private distinction between the interface and the implementation, derived classes, and constructors and destructors. I used macros to provide primitive parameterization. This was in use by mid-1980. Late that year, I was
ptg10564057 24 Notes to the Reader Chapter 1 able to present a set of language facilities supporting a coherent set of programming styles; see §1.2 .1 . In retrospect, I consider the introduction of constructors and destructors most significant. In the terminology of the time, ‘‘a constructor creates the execution environment for the member functions and the destructor reverses that.’’ Here is the root of C++’s strategies for resource man- agement (causing a demand for exceptions) and the key to many techniques for making user code short and clear. If there were other languages at the time that supported multiple constructors capa- ble of executing general code, I didn’t (and don’t) know of them. Destructors were new in C++. C++ was released commercially in October 1985. By then, I had added inlining (§12.1 .5, §16.2 .8), consts (§2.2 .3, §7.5, §16.2 .9), function overloading (§12.3), references (§7.7), operator overloading (§3.2 .1 .1, Chapter 18, Chapter 19), and virtual functions (§3.2 .3, §20.3 .2). Of these features, support for run-time polymorphism in the form of virtual functions was by far the most controversial. I knew its worth from Simula but found it impossible to convince most people in the systems programming world of its value. Systems programmers tended to view indirect function calls with suspicion, and people acquainted with other languages supporting object-oriented pro- gramming had a hard time believing that virtual functions could be fast enough to be useful in sys- tems code. Conversely, many programmers with an object-oriented background had (and many still have) a hard time getting used to the idea that you use virtual function calls only to express a choice that must be made at run time. The resistance to virtual functions may be related to a resistance to the idea that you can get better systems through more regular structure of code supported by a pro- gramming language. Many C programmers seem convinced that what really matters is complete flexibility and careful individual crafting of every detail of a program. My view was (and is) that we need every bit of help we can get from languages and tools: the inherent complexity of the sys- tems we are trying to build is always at the edge of what we can express. Much of the design of C++ was done on the blackboards of my colleagues. In the early years, the feedback from Stu Feldman, Alexander Fraser, Steve Johnson, Brian Kernighan, Doug McIlroy, and Dennis Ritchie was invaluable. In the second half of the 1980s, I continued to add language features in response to user com- ments. The most important of those were templates [Stroustrup,1988] and exception handling [Koenig,1990], which were considered experimental at the time the standards effort started. In the design of templates, I was forced to decide among flexibility, efficiency, and early type checking. At the time, nobody knew how to simultaneously get all three, and to compete with C-style code for demanding systems applications, I felt that I had to choose the first two properties. In retro- spect, I think the choice was the correct one, and the search for better type checking of templates continues [Gregor,2006] [Sutton,2011] [Stroustrup,2012a]. The design of exceptions focused on multilevel propagation of exceptions, the passing of arbitrary information to an error handler, and the integrations between exceptions and resource management by using local objects with destruc- tors to represent and release resources (what I clumsily called ‘‘Resource Acquisition Is Initial- ization’’; §13.3). I generalized C++’s inheritance mechanisms to support multiple base classes [Strous- trup,1987a]. This was called multiple inheritance and was considered difficult and controversial. I considered it far less important than templates or exceptions. Multiple inheritance of abstract classes (often called interfaces) is now universal in languages supporting static type checking and object-oriented programming.
ptg10564057 Section 1.4 .2 .1 Language Features and Library Facilities 25 The C++ language evolved hand in hand with some of the key library facilities presented in this book. For example, I designed the complex [Stroustrup,1984], vector, stack, and (I/O) stream [Stroustrup,1985] classes together with the operator overloading mechanisms. The first string and list classes were developed by Jonathan Shopiro and me as part of the same effort. Jonathan’s string and list classes were the first to see extensive use as part of a library. The string class from the standard C++ library has its roots in these early efforts. The task library described in [Strous- trup,1987b] was part of the first ‘‘C with Classes’’ program ever written in 1980. I wrote it and its associated classes to support Simula-style simulations. Unfortunately, we had to wait until 2011 (30 years!) to get concurrency support standardized and universally available (§1.4 .4 .2, §5.3, Chap- ter 41). The development of the template facility was influenced by a variety of vector, map, list, and sort templates devised by Andrew Koenig, Alex Stepanov, me, and others. C++ grew up in an environment with a multitude of established and experimental programming languages (e.g., Ada [Ichbiah,1979], Algol 68 [Woodward,1974], and ML [Paulson,1996]). At the time, I was comfortable in about 25 languages, and their influences on C++ are documented in [Stroustrup,1994] and [Stroustrup,2007]. However, the determining influences always came from the applications I encountered. That was a deliberate policy to have the development of C++ ‘‘problem driven’’ rather than imitative. 1.4.3 The 1998 Standard The explosive growth of C++ use caused some changes. Sometime during 1987, it became clear that formal standardization of C++ was inevitable and that we needed to start preparing the ground for a standardization effort [Stroustrup,1994]. The result was a conscious effort to maintain contact between implementers of C++ compilers and major users. This was done through paper and elec- tronic mail and through face-to-face meetings at C++ conferences and elsewhere. AT&T Bell Labs made a major contribution to C++ and its wider community by allowing me to share drafts of revised versions of the C++ reference manual with implementers and users. Because many of those people worked for companies that could be seen as competing with AT&T, the significance of this contribution should not be underestimated. A less enlightened company could have caused major problems of language fragmentation simply by doing nothing. As it hap- pened, about a hundred individuals from dozens of organizations read and commented on what became the generally accepted reference manual and the base document for the ANSI C++ stan- dardization effort. Their names can be found in The Annotated C++ Reference Manual (‘‘the ARM’’) [Ellis,1989]. The X3J16 committee of ANSI was convened in December 1989 at the ini- tiative of Hewlett-Packard. In June 1991, this ANSI (American national) standardization of C++ became part of an ISO (international) standardization effort for C++ and named WG21. From 1990, these joint C++ standards committees have been the main forum for the evolution of C++ and the refinement of its definition. I served on these committees throughout. In particular, as the chairman of the working group for extensions (later called the evolution group), I was directly responsible for handling proposals for major changes to C++ and the addition of new language fea- tures. An initial draft standard for public review was produced in April 1995. The first ISO C++ standard (ISO/IEC 14882-1998) [C++,1998] was ratified by a 22-0 national vote in 1998. A ‘‘bug fix release’’ of this standard was issued in 2003, so you sometimes hear people refer to C++03, but that is essentially the same language as C++98.
ptg10564057 26 Notes to the Reader Chapter 1 1.4 .3.1 Language Features By the time the ANSI and ISO standards efforts started, most major language features were in place and documented in the ARM [Ellis,1989]. Consequently, most of the work involved refinement of features and their specification. The template mechanisms, in particular, benefited from much detailed work. Namespaces were introduced to cope with the increased size of C++ programs and the increased number of libraries. At the initiative of Dmitry Lenkov from Hewett-Packard, mini- mal facilities to use run-time type information (RTTI; Chapter 22) were introduced. I had left such facilities out of C++ because I had found them seriously overused in Simula. I tried to get a facility for optional conservative garbage collection accepted, but failed. We had to wait until the 2011 standard for that. Clearly, the 1998 language was far superior in features and in particular in the detail of specifi- cation to the 1989 language. However, not all changes were improvements. In addition to the inevitable minor mistakes, two major features were added that in retrospect should not have been: • Exception specifications provide run-time enforcement of which exceptions a function is allowed to throw. They were added at the energetic initiative of people from Sun Microsys- tems. Exception specifications turned out to be worse than useless for improving readabil- ity, reliability, and performance. They are deprecated (scheduled for future removal) in the 2011 standard. The 2011 standard introduced noexcept (§13.5 .1 .1) as a simpler solution to many of the problems that exception specifications were supposed to address. • It was always obvious that separate compilation of templates and their uses would be ideal [Stroustrup,1994]. How to achieve that under the constraints from real-world uses of tem- plates was not at all obvious. After a long debate in the committee, a compromise was reached and something called export templates were specified as part of the 1998 standard. It was not an elegant solution to the problem, only one vendor implemented export (the Edi- son Design Group), and the feature was removed from the 2011 standard. We are still look- ing for a solution. My opinion is that the fundamental problem is not separate compilation in itself, but that the distinction between interface and implementation of a template is not well specified. Thus, export solved the wrong problem. In the future, language support for ‘‘concepts’’ (§24.3) may help by providing precise specification of template requirements. This is an area of active research and design [Sutton,2011] [Stroustrup,2012a]. 1.4 .3.2 The Standard Library The greatest and most important innovation in the 1998 standard was the inclusion of the STL, a framework of algorithms and containers, in the standard library (§4.4, §4.5, Chapter 31, Chapter 32, Chapter 33). It was the work of Alex Stepanov (with Dave Musser, Meng Le, and others) based on more than a decade’s work on generic programming. Andrew Koenig, Beman Dawes, and I did much to help get the STL accepted [Stroustrup,2007]. The STL has been massively influential within the C++ community and beyond. Except for the STL, the standard library was a bit of a hodgepodge of components, rather than a unified design. I had failed to ship a sufficiently large foundation library with Release 1.0 of C++ [Stroustrup,1993], and an unhelpful (non-research) AT&T manager had prevented my colleagues and me from rectifying that mistake for Release 2.0 . That meant that every major organization (such as Borland, IBM, Microsoft, and Texas Instruments) had its own foundation library by the
ptg10564057 Section 1.4 .3 .2 The Standard Library 27 time the standards work started. Thus, the committee was limited to a patchwork of components based on what had always been available (e.g ., the complex library), what could be added without interfering with the major vendor’s libraries, and what was needed to ensure cooperation among different nonstandard libraries. The standard-library string (§4.2, Chapter 36) had its origins in early work by Jonathan Shopiro and me at Bell Labs but was revised and extended by several different individuals and groups dur- ing standardization. The valarray library for numerical computation (§40.5) is primarily the work of Kent Budge. Jerry Schwarz transformed my streams library (§1.4 .2.1) into the iostreams library (§4.3, Chapter 38) using Andrew Koenig’s manipulator technique (§38.4 .5 .2) and other ideas. The iostreams library was further refined during standardization, where the bulk of the work was done by Jerry Schwarz, Nathan Myers, and Norihiro Kumagai. By commercial standards the C++98 standard library is tiny. For example, there is no standard GUI, database access library, or Web application library. Such libraries are widely available but are not part of the ISO standard. The reasons for that are practical and commercial, rather than techni- cal. However, the C standard library was (and is) many influential people’s measure of a standard library, and compared to that, the C++ standard library is huge. 1.4.4 The 2011 Standard The current C++, C++11, known for years as C++0x, is the work of the members of WG21. The committee worked under increasingly onerous self-imposed processes and procedures. These pro- cesses probably led to a better (and more rigorous) specification, but they also limited innovation [Stroustrup,2007]. An initial draft standard for public review was produced in 2009. The second ISO C++ standard (ISO/IEC 14882-2011) [C++,2011] was ratified by a 21-0 national vote in August 2011. One reason for the long gap between the two standards is that most members of the committee (including me) were under the mistaken impression that the ISO rules required a ‘‘waiting period’’ after a standard was issued before starting work on new features. Consequently, serious work on new language features did not start until 2002. Other reasons included the increased size of modern languages and their foundation libraries. In terms of pages of standards text, the language grew by about 30% and the standard library by about 100%. Much of the increase was due to more detailed specification, rather than new functionality. Also, the work on a new C++ standard obviously had to take great care not to compromise older code through incompatible changes. There are billions of lines of C++ code in use that the committee must not break. The overall aims for the C++11 effort were: • Make C++ a better language for systems programming and library building. • Make C++ easier to teach and learn. The aims are documented and detailed in [Stroustrup,2007]. A major effort was made to make concurrent systems programming type-safe and portable. This involved a memory model (§41.2) and a set of facilities for lock-free programming (§41.3), which is primarily the work of Hans Boehm, Brian McKnight, and others. On top of that, we added the threads library. Pete Becker, Peter Dimov, Howard Hinnant, William Kempf, Anthony Williams, and others did massive amounts of work on that. To provide an example of what can be achieved on top of the basic concurrency facilities, I proposed work on ‘‘a way to exchange
ptg10564057 28 Notes to the Reader Chapter 1 information between tasks without explicit use of a lock,’’ which became futures and async() (§5.3 .5); Lawrence Crowl and Detlef Vollmann did most of the work on that. Concurrency is an area where a complete and detailed listing of who did what and why would require a very long paper. Here, I can’t even try. 1.4 .4.1 Language Features The list of language features and standard-library facilities added to C++98 to get C++11 is pre- sented in §44.2. With the exception of concurrency support, every addition to the language could be deemed ‘‘minor,’’ but doing so would miss the point: language features are meant to be used in combination to write better programs. By ‘‘better’’ I mean easier to read, easier to write, more ele- gant, less error-prone, more maintainable, faster-running, consuming fewer resources, etc. Here are what I consider the most widely useful new ‘‘building bricks’’ affecting the style of C++11 code with references to the text and their primary authors: • Control of defaults: =delete and =default: §3.3 .4, §17.6 .1, §17.6 .4; Lawrence Crowl and Bjarne Stroustrup. • Deducing the type of an object from its initializer, auto: §2.2 .2, §6.3.6 .1; Bjarne Stroustrup. I first designed and implemented auto in 1983 but had to remove it because of C compatibil- ity problems. • Generalized constant expression evaluation (including literal types), constexpr: §2.2 .3, §10.4, §12.1 .6; Gabriel Dos Reis and Bjarne Stroustrup [DosReis,2010]. • In-class member initializers: §17.4.4; Michael Spertus and Bill Seymour. • Inheriting constructors: §20.3 .5 .1; Bjarne Stroustrup, Michael Wong, and Michel Michaud. • Lambda expressions, a way of implicitly defining function objects at the point of their use in an expression: §3.4 .3, §11.4; Jaakko Jarvi. • Move semantics, a way of transmitting information without copying: §3.3 .2, §17.5 .2; Howard Hinnant. • A way of stating that a function may not throw exceptions noexcept: §13.5 .1 .1; David Abra- hams, Rani Sharoni, and Doug Gregor. • A proper name for the null pointer, §7.2 .2; Herb Sutter and Bjarne Stroustrup. • The range-for statement: §2.2 .5, §9.5 .1; Thorsten Ottosen and Bjarne Stroustrup. • Override controls: final and override: §20.3 .4 . Alisdair Meredith, Chris Uzdavinis, and Ville Voutilainen. • Type aliases, a mechanism for providing an alias for a type or a template. In particular, a way of defining a template by binding some arguments of another template: §3.4 .5, §23.6; Bjarne Stroustrup and Gabriel Dos Reis. • Typed and scoped enumerations: enum class: §8.4 .1; David E. Miller, Herb Sutter, and Bjarne Stroustrup. • Universal and uniform initialization (including arbitrary-length initializer lists and protec- tion against narrowing): §2.2 .2, §3.2 .1 .3, §6.3 .5, §17.3 .1, §17.3 .4; Bjarne Stroustrup and Gabriel Dos Reis. • Variadic templates, a mechanism for passing an arbitrary number of arguments of arbitrary types to a template: §3.4.4, §28.6; Doug Gregor and Jaakko Jarvi.
ptg10564057 Section 1.4 .4 .1 Language Features 29 Many more people than can be listed here deserve to be mentioned. The technical reports to the committee [WG21] and my C++11 FAQ [Stroustrup,2010a] give many of the names. The minutes of the committee’s working groups mention more still. The reason my name appears so often is (I hope) not vanity, but simply that I chose to work on what I consider important. These are features that will be pervasive in good code. Their major role is to flesh out the C++ feature set to better support programming styles (§1.2 .1). They are the foundation of the synthesis that is C++11. Much work went into a proposal that did not make it into the standard. ‘‘Concepts’’ was a facil- ity for specifying and checking requirements for template arguments [Gregor,2006] based on previ- ous research (e.g ., [Stroustrup,1994] [Siek,2000] [DosReis,2006]) and extensive work in the com- mittee. It was designed, specified, implemented, and tested, but by a large majority the committee decided that the proposal was not yet ready. Had we been able to refine ‘‘concepts,’’ it would have been the most important single feature in C++11 (its only competitor for that title is concurrency support). However, the committee decided against ‘‘concepts’’ on the grounds of complexity, diffi- culty of use, and compile-time performance [Stroustrup,2010b]. I think we (the committee) did the right thing with ‘‘concepts’’ for C++11, but this feature really was ‘‘the one that got away.’’ This is currently a field of active research and design [Sutton,2011] [Stroustrup,2012a]. 1.4 .4.2 Standard Library The work on what became the C++11 standard library started with a standards committee technical report (‘‘TR1’’). Initially, Matt Austern was the head of the Library Working Group, and later Howard Hinnant took over until we shipped the final draft standard in 2011. As for language features, I’ll only list a few standard-library components with references to the text and the names of the individuals most closely associated with them. For a more detailed list, see §44.2 .2 . Some components, such as unordered_map (hash tables), were ones we simply didn’t manage to finish in time for the C++98 standard. Many others, such as unique_ptr and function were part of a technical report (TR1) based on Boost libraries. Boost is a volunteer organization created to provide useful library components based on the STL [Boost]. • Hashed containers, such as unordered_map: §31.4 .3; Matt Austern. • The basic concurrency library components, such as thread, mutex, and lock: §5.3, §42.2; Pete Becker, Peter Dimov, Howard Hinnant, William Kempf, Anthony Williams, and more. • Launching asynchronous computation and returning results, future, promise, and async(): §5.3 .5, §42.4 .6; Detlef Vollmann, Lawrence Crowl, Bjarne Stroustrup, and Herb Sutter. • The garbage collection interface: §34.5; Michael Spertus and Hans Boehm. • A regular expression library, regexp: §5.5, Chapter 37; John Maddock. • A random number library: §5.6 .3, §40.7; Jens Maurer and Walter Brown. It was about time. I shipped the first random number library with ‘‘C with Classes’’ in 1980. Several utility components were tried out in Boost: • A pointer for simply and efficiently passing resources, unique_ptr: §5.2 .1, §34.3 .1; Howard E. Hinnant. This was originally called move_ptr and is what auto_ptr should have been had we known how to do so for C++98. • A pointer for representing shared ownership, shared_ptr: §5.2 .1, §34.3 .2; Peter Dimov. A successor to the C++98 counted_ptr proposal from Greg Colvin.
ptg10564057 30 Notes to the Reader Chapter 1 • The tuple library: §5.4 .3, §28.5, §34.2 .4.2; Jaakko Jarvi and Gary Powell. They credit a long list of contributors, including Doug Gregor, David Abrahams, and Jeremy Siek. • The general bind(): §33.5 .1; Peter Dimov. His acknowledgments list a veritable who’s who of Boost (including Doug Gregor, John Maddock, Dave Abrahams, and Jaakko Jarvi). • The function type for holding callable objects: §33.5 .3; Doug Gregor. He credits William Kempf and others with contributions. 1.4.5 What is C++ used for? By now (2013), C++ is used just about everywhere: it is in your computer, your phone, your car, probably even in your camera. You don’t usually see it. C++ is a systems programming language, and its most pervasive uses are deep in the infrastructure where we, as users, never look. C++ is used by millions of programmers in essentially every application domain. Billions (thousands of millions) of lines of C++ are currently deployed. This massive use is supported by half a dozen independent implementations, many thousands of libraries, hundreds of textbooks, and dozens of websites. Training and education at a variety of levels are widely available. Early applications tended to have a strong systems programming flavor. For example, several early operating systems have been written in C++: [Campbell,1987] (academic), [Rozier,1988] (real time), [Berg,1995] (high-throughput I/O). Many current ones (e.g ., Windows, Apple’s OS, Linux, and most portable-device OSs) have key parts done in C++. Your cellphone and Internet routers are most likely written in C++. I consider uncompromising low-level efficiency essential for C++. This allows us to use C++ to write device drivers and other software that rely on direct manipulation of hardware under real-time constraints. In such code, predictability of performance is at least as important as raw speed. Often, so is the compactness of the resulting system. C++ was designed so that every language feature is usable in code under severe time and space con- straints (§1.2.4) [Stroustrup,1994,§4.5]. Some of today’s most visible and widely used systems have their critical parts written in C++. Examples are Amadeus (airline ticketing), Amazon (Web commerce), Bloomberg (financial infor- mation), Google (Web search), and Facebook (social media). Many other programming languages and technologies depend critically on C++’s performance and reliability in their implementation. Examples include the most widely used Java Virtual Machines (e.g ., Oracle’s HotSpot), JavaScript interpreters (e.g ., Google’s V8), browsers (e.g ., Microsoft’s Internet Explorer, Mozilla’s Firefox, Apple’s Safari, and Google’s Chrome), and application frameworks (e.g ., Microsoft’s .NET Web services framework). I consider C++ to have unique strengths in the area of infrastructure software [Stroustrup,2012a]. Most applications have sections of code that are critical for acceptable performance. However, the largest amount of code is not in such sections. For most code, maintainability, ease of exten- sion, and ease of testing are key. C++’s support for these concerns has led to its widespread use in areas where reliability is a must and where requirements change significantly over time. Examples are financial systems, telecommunications, device control, and military applications. For decades, the central control of the U.S. long-distance telephone system has relied on C++, and every 800 call (i.e., a call paid for by the called party) has been routed by a C++ program [Kamath,1993]. Many such applications are large and long-lived. As a result, stability, compatibility, and scalability have been constant concerns in the development of C++. Multimillion-line C++ programs are common.
ptg10564057 Section 1.4 .5 What is C++ used for? 31 Games is another area where a multiplicity of languages and tools need to coexist with a lan- guage providing uncompromising efficiency (often on ‘‘unusual’’ hardware). Thus, games has been another major applications area for C++. What used to be called systems programming is widely found in embedded systems, so it is not surprising to find massive use of C++ in demanding embedded systems projects, including com- puter tomography (CAT scanners), flight control software (e.g ., Lockheed-Martin), rocket control, ship’s engines (e.g., the control of the world’s largest marine diesel engines from MAN), automo- bile software (e.g ., BMW), and wind turbine control (e.g ., Vesta). C++ wasn’t specifically designed with numerical computation in mind. However, much numer- ical, scientific, and engineering computation is done in C++. A major reason for this is that tradi- tional numerical work must often be combined with graphics and with computations relying on data structures that don’t fit into the traditional Fortran mold (e.g ., [Root,1995]). I am particularly pleased to see C++ used in major scientific endeavors, such as the Human Genome Project, NASA’s Mars Rovers, CERN’s search for the fundamentals of the universe, and many others. C++’s ability to be used effectively for applications that require work in a variety of application areas is an important strength. Applications that involve local- and wide-area networking, numer- ics, graphics, user interaction, and database access are common. Traditionally, such application areas were considered distinct and were served by distinct technical communities using a variety of programming languages. However, C++ is widely used in all of those areas, and more. It is designed so that C++ code can coexist with code written in other languages. Here, again, C++’s stability over decades is important. Furthermore, no really major system is written 100% in a sin- gle language. Thus, C++’s original design aim of interoperability becomes significant. Major applications are not written in just the raw language. C++ is supported by a variety of libraries (beyond the ISO C++ standard library) and tool sets, such as Boost [Boost] (portable foun- dation libraries), POCO (Web development), QT (cross-platform application development), wxWidgets (a cross-platform GUI library), WebKit (a layout engine library for Web browsers), CGAL (computational geometry), QuickFix (Financial Information eXchange), OpenCV (real-time image processing), and Root [Root,1995] (High-Energy Physics). There are many thousands of C++ libraries, so keeping up with them all is impossible. 1.5 Advice Each chapter contains an ‘‘Advice’’ section with a set of concrete recommendations related to its contents. Such advice consists of rough rules of thumb, not immutable laws. A piece of advice should be applied only where reasonable. There is no substitute for intelligence, experience, com- mon sense, and good taste. I find rules of the form ‘‘never do this’’ unhelpful. Consequently, most advice is phrased as suggestions for what to do. Negative suggestions tend not to be phrased as absolute prohibitions and I try to suggest alternatives. I know of no major feature of C++ that I have not seen put to good use. The ‘‘Advice’’ sections do not contain explanations. Instead, each piece of advice is accompa- nied by a reference to an appropriate section of the book. For starters, here are a few high-level recommendations derived from the sections on design, learning, and history of C++:
ptg10564057 32 Notes to the Reader Chapter 1 [1] Represent ideas (concepts) directly in code, for example, as a function, a class, or an enu- meration; §1.2 . [2] Aim for your code to be both elegant and efficient; §1.2. [3] Don’t overabstract; §1.2 . [4] Focus design on the provision of elegant and efficient abstractions, possibly presented as libraries; §1.2. [5] Represent relationships among ideas directly in code, for example, through parameteriza- tion or a class hierarchy; §1.2 .1 . [6] Represent independent ideas separately in code, for example, avoid mutual dependencies among classes; §1.2.1 . [7] C++ is not just object-oriented; §1.2 .1 . [8] C++ is not just for generic programming; §1.2.1 . [9] Prefer solutions that can be statically checked; §1.2 .1 . [10] Make resources explicit (represent them as class objects); §1.2 .1, §1.4 .2 .1 . [11] Express simple ideas simply; §1.2 .1 . [12] Use libraries, especially the standard library, rather than trying to build everything from scratch; §1.2 .1 . [13] Use a type-rich style of programming; §1.2 .2 . [14] Low-level code is not necessarily efficient; don’t avoid classes, templates, and standard- library components out of fear of performance problems; §1.2 .4, §1.3 .3 . [15] If data has an invariant, encapsulate it; §1.3 .2 . [16] C++ is not just C with a few extensions; §1.3.3 . In general: To write a good program takes intelligence, taste, and patience. You are not going to get it right the first time. Experiment! 1.6 References [Austern,2003] Matt Austern et al.: Untangling the Balancing and Searching of Balanced Binary Search Trees. Software – Practice & Experience. Vol 33, Issue 13. November 2003. [Barron,1963] D. W. Barron et al.: The main features of CPL. The Computer Journal. 6 (2): 134. (1963). comjnl.oxfordjournals.org/content/6/2/134.full.pdf+html. [Barton,1994] J. J. Barton and L. R . Nackman: Scientific and Engineering C++: An Intro- duction with Advanced Techniques and Examples. Addison-Wesley. Read- ing, Massachusetts. 1994. ISBN 0-201-53393 -6 . [Berg,1995] William Berg, Marshall Cline, and Mike Girou: Lessons Learned from the OS/400 OO Project. CACM. Vol. 38, No. 10. October 1995. [Boehm,2008] Hans-J . Boehm and Sarita V. Adve: Foundations of the C++ concurrency memory model. ACM PLDI’08. [Boost] The Boost library collection. www.boost.org. [Budge,1992] Kent Budge, J. S. Perry, and A. C. Robinson: High-Performance Scientific Computation Using C++. Proc. USENIX C++ Conference. Portland, Ore- gon. August 1992.
ptg10564057 Section 1.6 References 33 [C,1990] X3 Secretariat: Standard – The C Language. X3J11/90-013. ISO Standard ISO/IEC 9899-1990. Computer and Business Equipment Manufacturers Association. Washington, DC. [C,1999] ISO/IEC 9899. Standard – The C Language. X3J11/90-013-1999. [C,2011] ISO/IEC 9899. Standard – The C Language. X3J11/90-013-2011. [C++,1998] ISO/IEC JTC1/SC22/WG21: International Standard – The C++ Language. ISO/IEC 14882:1998. [C++Math,2010] International Standard – Extensions to the C++ Library to Support Mathe- matical Special Functions. ISO/IEC 29124:2010. [C++,2011] ISO/IEC JTC1/SC22/WG21: International Standard – The C++ Language. ISO/IEC 14882:2011. [Campbell,1987] Roy Campbell et al.: The Design of a Multiprocessor Operating System. Proc. USENIX C++ Conference. Santa Fe, New Mexico. November 1987. [Coplien,1995] James O. Coplien: Curiously Recurring Template Patterns. The C++ Report. February 1995. [Cox,2007] Russ Cox: Regular Expression Matching Can Be Simple And Fast. January 2007. swtch.com/̃rsc/regexp/regexp1.html. [Czarnecki,2000] K. Czarnecki and U. Eisenecker: Generative Programming: Methods, Tools, and Applications. Addison-Wesley. Reading, Massachusetts. 2000. ISBN 0-201-30977-7 . [Dahl,1970] O-J. Dahl, B. Myrhaug, and K. Nygaard: SIMULA Common Base Language. Norwegian Computing Center S-22 . Oslo, Norway. 1970. [Dahl,1972] O-J. Dahl and C. A. R . Hoare: Hierarchical Program Construction in Struc- tured Programming. Academic Press. New York. 1972. [Dean,2004] J. Dean and S. Ghemawat: MapReduce: Simplified Data Processing on Large Clusters. OSDI’04: Sixth Symposium on Operating System Design and Implementation. 2004. [Dechev,2010] D. Dechev, P. Pirkelbauer, and B. Stroustrup: Understanding and Effectively Preventing the ABA Problem in Descriptor-based Lock-free Designs. 13th IEEE Computer Society ISORC 2010 Symposium. May 2010. [DosReis,2006] Gabriel Dos Reis and Bjarne Stroustrup: Specifying C++ Concepts. POPL06. January 2006. [DosReis,2010] Gabriel Dos Reis and Bjarne Stroustrup: General Constant Expressions for System Programming Languages. SAC-2010. The 25th ACM Symposium On Applied Computing. March 2010. [DosReis,2011] Gabriel Dos Reis and Bjarne Stroustrup: A Principled, Complete, and Effi- cient Representation of C++. Journal of Mathematics in Computer Science. Vol. 5, Issue 3. 2011. [Ellis,1989] Margaret A. Ellis and Bjarne Stroustrup: The Annotated C++ Reference Manual. Addison-Wesley. Reading, Mass. 1990. ISBN 0-201-51459-1 . [Freeman,1992] Len Freeman and Chris Phillips: Parallel Numerical Algorithms. Prentice Hall. Englewood Cliffs, New Jersey. 1992. ISBN 0-13-651597-5 . [Friedl,1997]: Jeffrey E. F. Friedl: Mastering Regular Expressions. O’Reilly Media. Sebastopol, California. 1997. ISBN 978-1565922570.
ptg10564057 34 Notes to the Reader Chapter 1 [Gamma,1995] Erich Gamma et al.: Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley. Reading, Massachusetts. 1994. ISBN 0-201-63361-2 . [Gregor,2006] Douglas Gregor et al.: Concepts: Linguistic Support for Generic Program- ming in C++. OOPSLA’06. [Hennessy,2011] John L. Hennessy and David A. Patterson: Computer Architecture, Fifth Edi- tion: A Quantitative Approach. Morgan Kaufmann. San Francisco, Califor- nia. 2011. ISBN 978-0123838728. [Ichbiah,1979] Jean D. Ichbiah et al.: Rationale for the Design of the ADA Programming Language. SIGPLAN Notices. Vol. 14, No. 6 . June 1979. [Kamath,1993] Yogeesh H. Kamath, Ruth E. Smilan, and Jean G. Smith: Reaping Benefits with Object-Oriented Technology. AT&T Technical Journal. Vol. 72, No. 5. September/October 1993. [Kernighan,1978] Brian W. Kernighan and Dennis M. Ritchie: The C Programming Language. Prentice Hall. Englewood Cliffs, New Jersey. 1978. [Kernighan,1988] Brian W. Kernighan and Dennis M. Ritchie: The C Programming Language, Second Edition. Prentice-Hall. Englewood Cliffs, New Jersey. 1988. ISBN 0-13-110362-8 . [Knuth,1968] Donald E. Knuth: The Art of Computer Programming. Addison-Wesley. Reading, Massachusetts. 1968. [Koenig,1989] Andrew Koenig and Bjarne Stroustrup: C++: As close to C as possible – but no closer. The C++ Report. Vol. 1, No. 7 . July 1989. [Koenig,1990] A. R. Koenig and B. Stroustrup: Exception Handling for C++ (revised). Proc USENIX C++ Conference. April 1990. [Kolecki,2002] Joseph C. Kolecki: An Introduction to Tensors for Students of Physics and Engineering. NASA/TM-2002-211716. [Langer,2000] Angelika Langer and Klaus Kreft: Standard C++ IOStreams and Locales: Advanced Programmer’s Guide and Reference. Addison-Wesley. 2000. ISBN 978-0201183955. [McKenney] Paul E. McKenney: Is Parallel Programming Hard, And, If So, What Can You Do About It? kernel.org. Corvallis, Oregon. 2012. http://kernel.org/pub/linux/kernel/people/paulmck/perfbook/perfbook.html. [Maddock,2009] John Maddock: Boost.Regex. www.boost.org. 2009. [Orwell,1949] George Orwell: 1984. Secker and Warburg. London. 1949. [Paulson,1996] Larry C. Paulson: ML for the Working Programmer. Cambridge University Press. Cambridge. 1996. ISBN 0-521-56543-X . [Pirkelbauer,2009] P. Pirkelbauer, Y. Solodkyy, and B. Stroustrup: Design and Evaluation of C++ Open Multi-Methods. Science of Computer Programming. Elsevier Journal. June 2009. doi:10.1016/j.scico.2009.06 .002. [Richards,1980] Martin Richards and Colin Whitby-Strevens: BCPL – The Language and Its Compiler. Cambridge University Press. Cambridge. 1980. ISBN 0-521-21965-5 . [Root,1995] ROOT: A Data Analysis Framework. root.cern .ch. It seems appropriate to represent a tool from CERN, the birthplace of the World Wide Web, by a
ptg10564057 Section 1.6 References 35 Web address. [Rozier,1988] M. Rozier et al.: CHORUS Distributed Operating Systems. Computing Sys- tems. Vol. 1, No. 4 . Fall 1988. [Siek,2000] Jeremy G. Siek and Andrew Lumsdaine: Concept checking: Binding para- metric polymorphism in C++. Proc. First Workshop on C++ Template Pro- gramming. Erfurt, Germany. 2000. [Solodkyy,2012] Y. Solodkyy, G. Dos Reis, and B. Stroustrup: Open and Efficient Type Switch for C++. Proc. OOPSLA’12. [Stepanov,1994] Alexander Stepanov and Meng Lee: The Standard Template Library.HP Labs Technical Report HPL-94-34 (R. 1). 1994. [Stewart,1998] G. W. Stewart: Matrix Algorithms, Volume I. Basic Decompositions. SIAM. Philadelphia, Pennsylvania. 1998. [Stroustrup,1982] B. Stroustrup: Classes: An Abstract Data Type Facility for the C Language. Sigplan Notices. January 1982. The first public description of ‘‘C with Classes.’’ [Stroustrup,1984] B. Stroustrup: Operator Overloading in C++. Proc. IFIP WG2.4 Confer- ence on System Implementation Languages: Experience & Assessment. September 1984. [Stroustrup,1985] B. Stroustrup: An Extensible I/O Facility for C++. Proc. Summer 1985 USENIX Conference. [Stroustrup,1986] B. Stroustrup: The C++ Programming Language. Addison-Wesley. Read- ing, Massachusetts. 1986. ISBN 0-201-12078-X. [Stroustrup,1987] B. Stroustrup: Multiple Inheritance for C++. Proc. EUUG Spring Confer- ence. May 1987. [Stroustrup,1987b] B. Stroustrup and J. Shopiro: A Set of C Classes for Co-Routine Style Pro- gramming. Proc. USENIX C++ Conference. Santa Fe, New Mexico. November 1987. [Stroustrup,1988] B. Stroustrup: Parameterized Types for C++. Proc. USENIX C++ Confer- ence, Denver. 1988. [Stroustrup,1991] B. Stroustrup: The C++ Programming Language (Second Edition). Addi - son-Wesley. Reading, Massachusetts. 1991. ISBN 0-201-53992-6 . [Stroustrup,1993] B. Stroustrup: A History of C++: 1979-1991. Proc. ACM History of Pro- gramming Languages conference (HOPL-2). ACM Sigplan Notices. Vol 28, No 3. 1993. [Stroustrup,1994] B. Stroustrup: The Design and Evolution of C++. Addison-Wesley. Read- ing, Mass. 1994. ISBN 0-201-54330-3 . [Stroustrup,1997] B. Stroustrup: The C++ Programming Language, Third Edition. Addison- Wesley. Reading, Massachusetts. 1997. ISBN 0-201-88954-4 . Hardcover (‘‘Special’’) Edition. 2000. ISBN 0-201-70073-5 . [Stroustrup,2002] B. Stroustrup: C and C++: Siblings, C and C++: A Case for Compatibility, and C and C++: Case Studies in Compatibility. The C/C++ Users Journal. July-September 2002. www.stroustrup.com/papers.html. [Stroustrup,2007] B. Stroustrup: Evolving a language in and for the real world: C++ 1991-2006. ACM HOPL-III . June 2007.
ptg10564057 36 Notes to the Reader Chapter 1 [Stroustrup,2008] B. Stroustrup: Programming – Principles and Practice Using C++. Addi - son-Wesley. 2009. ISBN 0-321-54372-6 . [Stroustrup,2010a] B. Stroustrup: The C++11 FAQ. www.stroustrup.com/C++11FAQ.html. [Stroustrup,2010b] B. Stroustrup: The C++0x ‘‘Remove Concepts’’ Decision. Dr. Dobb’s Jour- nal. July 2009. [Stroustrup,2012a] B. Stroustrup and A. Sutton: A Concept Design for the STL. WG21 Techni- cal Report N3351==12-0041. January 2012. [Stroustrup,2012b] B. Stroustrup: Software Development for Infrastructure. Computer. January 2012. doi:10.1109/MC.2011.353 . [Sutton,2011] A. Sutton and B. Stroustrup: Design of Concept Libraries for C++. Proc. SLE 2011 (International Conference on Software Language Engineering). July 2011. [Tanenbaum,2007] Andrew S. Tanenbaum: Modern Operating Systems, Third Edition. Prentice Hall. Upper Saddle River, New Jersey. 2007. ISBN 0-13-600663 -9 . [Tsafrir,2009] Dan Tsafrir et al.: Minimizing Dependencies within Generic Classes for Faster and Smaller Programs. ACM OOPSLA’09. October 2009. [Unicode,1996] The Unicode Consortium: The Unicode Standard, Version 2.0 . Addison- Wesley. Reading, Massachusetts. 1996. ISBN 0-201-48345-9 . [UNIX,1985] UNIX Time-Sharing System: Programmer’s Manual. Research Version, Tenth Edition. AT&T Bell Laboratories, Murray Hill, New Jersey. February 1985. [Vandevoorde,2002] David Vandevoorde and Nicolai M. Josuttis: C++ Templates: The Complete Guide. Addison-Wesley. 2002. ISBN 0-201-73484-2. [Veldhuizen,1995] Todd Veldhuizen: Expression Templates. The C++ Report. June 1995. [Veldhuizen,2003] Todd L. Veldhuizen: C++ Templates are Turing Complete. Indiana Univer- sity Computer Science Technical Report. 2003. [Vitter,1985] Jefferey Scott Vitter: Random Sampling with a Reservoir. ACM Transac- tions on Mathematical Software, Vol. 11, No. 1 . 1985. [WG21] ISO SC22/WG21 The C++ Programming Language Standards Committee: Document Archive. www.open-std.org/jtc1/sc22/wg21. [Williams,2012] Anthony Williams: C++ Concurrency in Action – Practical Multithreading. Manning Publications Co. ISBN 978-1933988771. [Wilson,1996] Gregory V. Wilson and Paul Lu (editors): Parallel Programming Using C++. The MIT Press. Cambridge, Mass. 1996. ISBN 0-262-73118-5 . [Wood,1999] Alistair Wood: Introduction to Numerical Analysis. Addison-Wesley. Read- ing, Massachusetts. 1999. ISBN 0-201-34291-X . [Woodward,1974] P. M. Woodward and S. G. Bond: Algol 68-R Users Guide. Her Majesty’s Stationery Office. London. 1974.
ptg10564057 2 A Tour of C++: The Basics The first thing we do, let’s kill all the language lawyers. – Henry VI, Part II • Introduction • The Basics Hello, World!; Types, Variables, and Arithmetic; Constants; Tests and Loops; Pointers, Arrays, and Loops • User-Defined Types Structures; Classes; Enumerations • Modularity Separate Compilation; Namespaces; Error Handling • Postscript • Advice 2.1 Introduction The aim of this chapter and the next three is to give you an idea of what C++ is, without going into a lot of details. This chapter informally presents the notation of C++, C++’s model of memory and computation, and the basic mechanisms for organizing code into a program. These are the lan- guage facilities supporting the styles most often seen in C and sometimes called procedural pro- gramming. Chapter 3 follows up by presenting C++’s abstraction mechanisms. Chapter 4 and Chapter 5 give examples of standard-library facilities. The assumption is that you have programmed before. If not, please consider reading a text- book, such as Programming: Principles and Practice Using C++ [Stroustrup,2009], before contin- uing here. Even if you have programmed before, the language you used or the applications you wrote may be very different from the style of C++ presented here. If you find this ‘‘lightning tour’’ confusing, skip to the more systematic presentation starting in Chapter 6.
ptg10564057 38 A Tour of C++: The Basics Chapter 2 This tour of C++ saves us from a strictly bottom-up presentation of language and library facili- ties by enabling the use of a rich set of facilities even in early chapters. For example, loops are not discussed in detail until Chapter 10, but they will be used in obvious ways long before that. Simi- larly, the detailed description of classes, templates, free-store use, and the standard library are spread over many chapters, but standard-library types, such as vector, string, complex, map, unique_ptr, and ostream, are used freely where needed to improve code examples. As an analogy, think of a short sightseeing tour of a city, such as Copenhagen or New York. In just a few hours, you are given a quick peek at the major attractions, told a few background stories, and usually given some suggestions about what to see next. You do not know the city after such a tour. You do not understand all you have seen and heard. To really know a city, you have to live in it, often for years. However, with a bit of luck, you will have gained a bit of an overview, a notion of what is special about the city, and ideas of what might be of interest to you. After the tour, the real exploration can begin. This tour presents C++ as an integrated whole, rather than as a layer cake. Consequently, it does not identify language features as present in C, part of C++98, or new in C++11. Such histori- cal information can be found in §1.4 and Chapter 44. 2.2 The Basics C++ is a compiled language. For a program to run, its source text has to be processed by a com- piler, producing object files, which are combined by a linker yielding an executable program. A C++ program typically consists of many source code files (usually simply called source files). source file 1 source file 2 compile compile object file 1 object file 2 link executable file An executable program is created for a specific hardware/system combination; it is not portable, say, from a Mac to a Windows PC. When we talk about portability of C++ programs, we usually mean portability of source code; that is, the source code can be successfully compiled and run on a variety of systems. The ISO C++ standard defines two kinds of entities: • Core language features, such as built-in types (e.g ., char and int) and loops (e.g ., for-state- ments and while-statements) • Standard-library components, such as containers (e.g ., vector and map) and I/O operations (e.g., << and getline()) The standard-library components are perfectly ordinary C++ code provided by every C++ imple- mentation. That is, the C++ standard library can be implemented in C++ itself (and is with very minor uses of machine code for things such as thread context switching). This implies that C++ is sufficiently expressive and efficient for the most demanding systems programming tasks. C++ is a statically typed language. That is, the type of every entity (e.g ., object, value, name, and expression) must be known to the compiler at its point of use. The type of an object determines the set of operations applicable to it.
ptg10564057 Section 2.2 .1 Hello, World! 39 2.2.1 Hello, World! The minimal C++ program is int main() { } // the minimal C++ program This defines a function called main, which takes no arguments and does nothing (§15.4). Curly braces, {}, express grouping in C++. Here, they indicate the start and end of the function body. The double slash, //, begins a comment that extends to the end of the line. A comment is for the human reader; the compiler ignores comments. Every C++ program must have exactly one global function named main(). The program starts by executing that function. The int value returned by main(), if any, is the program’s return value to ‘‘the system.’’ If no value is returned, the system will receive a value indicating successful comple- tion. A nonzero value from main() indicates failure. Not every operating system and execution environment make use of that return value: Linux/Unix-based environments often do, but Win- dows-based environments rarely do. Typically, a program produces some output. Here is a program that writes Hello, World!: #include <iostream> int main() { std::cout << "Hello, World!\n"; } The line #include <iostream> instructs the compiler to include the declarations of the standard stream I/O facilities as found in iostream. Without these declarations, the expression std::cout << "Hello, World!\n" would make no sense. The operator << (‘‘put to’’) writes its second argument onto its first. In this case, the string literal "Hello, World!\n" is written onto the standard output stream std::cout. A string literal is a sequence of characters surrounded by double quotes. In a string literal, the backslash character \ followed by another character denotes a single ‘‘special character.’’ In this case, \n is the newline character, so that the characters written are Hello, World! followed by a newline. The std:: specifies that the name cout is to be found in the standard-library namespace (§2.4 .2, Chapter 14). I usually leave out the std:: when discussing standard features; §2.4 .2 shows how to make names from a namespace visible without explicit qualification. Essentially all executable code is placed in functions and called directly or indirectly from main(). For example: #include <iostream> using namespace std; // make names from std visible without std:: (§2.4 .2) double square(double x) // square a double precision floating-point number { return x∗x; }
ptg10564057 40 A Tour of C++: The Basics Chapter 2 void print_square(double x) { cout << "the square of " << x << " is " << square(x) << "\n"; } int main() { print_square(1.234); // print: the square of 1.234 is 1.52276 } A ‘‘return type’’ void indicates that a function does not return a value. 2.2.2 Types, Variables, and Arithmetic Every name and every expression has a type that determines the operations that may be performed on it. For example, the declaration int inch; specifies that inch is of type int; that is, inch is an integer variable. A declaration is a statement that introduces a name into the program. It specifies a type for the named entity: •A type defines a set of possible values and a set of operations (for an object). •A n object is some memory that holds a value of some type. •A value is a set of bits interpreted according to a type. •A variable is a named object. C++ offers a variety of fundamental types. For example: bool // Boolean, possible values are true and false char // character, for example, 'a', ' z', and '9' int // integer, for example, 1, 42, and 1066 double // double-precision floating-point number, for example, 3.14 and 299793.0 Each fundamental type corresponds directly to hardware facilities and has a fixed size that deter- mines the range of values that can be stored in it: bool: char: int: double: A char variable is of the natural size to hold a character on a given machine (typically an 8-bit byte), and the sizes of other types are quoted in multiples of the size of a char. The size of a type is implementation-defined (i.e., it can vary among different machines) and can be obtained by the sizeof operator; for example, sizeof(char) equals 1 and sizeof(int) is often 4. The arithmetic operators can be used for appropriate combinations of these types:
ptg10564057 Section 2.2 .2 Types, Variables, and Arithmetic 41 x+y // plus +x // unary plus x−y // minus −x // unary minus x∗y/ / multiply x/y // divide x%y // remainder (modulus) for integers So can the comparison operators: x==y // equal x!=y // not equal x<y // less than x>y // greater than x<=y // less than or equal x>=y // greater than or equal In assignments and in arithmetic operations, C++ performs all meaningful conversions (§10.5 .3) between the basic types so that they can be mixed freely: void some_function() // function that doesn’t return a value { double d = 2.2; // initialize floating-point number inti=7; // initialize integer d=d+i; // assign sum to d i=d∗i; // assign product to i (truncating the double d*i to an int) } Note that = is the assignment operator and == tests equality. C++ offers a variety of notations for expressing initialization, such as the = used above, and a universal form based on curly-brace-delimited initializer lists: double d1 = 2.3; double d2 {2.3}; complex<double> z = 1; // a complex number with double-precision floating-point scalars complex<double> z2 {d1,d2}; complex<double> z3 = {1,2}; // the = is optional with { ... } vector<int> v {1,2,3,4,5,6}; // a vector of ints The = form is traditional and dates back to C, but if in doubt, use the general {}-list form (§6.3 .5 .2). If nothing else, it saves you from conversions that lose information (narrowing conversions; §10.5): int i1 = 7.2; // i1 becomes 7 int i2 {7.2}; // error: floating-point to integer conversion int i3 = {7.2}; // error: floating-point to integer conversion (the = is redundant) A constant (§2.2.3) cannot be left uninitialized and a variable should only be left uninitialized in extremely rare circumstances. Don’t introduce a name until you have a suitable value for it. User- defined types (such as string, vector, Matrix, Motor_controller, and Orc_warrior) can be defined to be implicitly initialized (§3.2 .1.1).
ptg10564057 42 A Tour of C++: The Basics Chapter 2 When defining a variable, you don’t actually need to state its type explicitly when it can be deduced from the initializer: auto b = true; // a bool auto ch = 'x'; // a char auto i = 123; // an int auto d = 1.2; // a double auto z = sqrt(y); // z has the type of whatever sqrt(y) returns With auto, we use the = syntax because there is no type conversion involved that might cause prob- lems (§6.3 .6 .2). We u s e auto where we don’t have a specific reason to mention the type explicitly. ‘‘Specific reasons’’ include: • The definition is in a large scope where we want to make the type clearly visible to readers of our code. • We want to be explicit about a variable’s range or precision (e.g ., double rather than float). Using auto, we avoid redundancy and writing long type names. This is especially important in generic programming where the exact type of an object can be hard for the programmer to know and the type names can be quite long (§4.5 .1). In addition to the conventional arithmetic and logical operators (§10.3), C++ offers more spe- cific operations for modifying a variable: x+=y //x=x+y ++x // increment: x = x+1 x−=y //x=x-y −−x // decrement: x = x-1 x∗=y // scaling: x = x*y x/=y // scaling: x = x/y x%=y //x=x%y These operators are concise, convenient, and very frequently used. 2.2.3 Constants C++ supports two notions of immutability (§7.5): • const: meaning roughly ‘‘I promise not to change this value’’ (§7.5). This is used primarily to specify interfaces, so that data can be passed to functions without fear of it being modi- fied. The compiler enforces the promise made by const. • constexpr: meaning roughly ‘‘to be evaluated at compile time’’ (§10.4). This is used primar- ily to specify constants, to allow placement of data in memory where it is unlikely to be cor- rupted, and for performance. For example: const int dmv = 17; // dmv is a named constant int var = 17; // var is not a constant constexpr double max1 = 1.4∗square(dmv); // OK if square(17) is a constant expression constexpr double max2 = 1.4∗square(var); // error: var is not a constant expression const double max3 = 1.4∗square(var); // OK, may be evaluated at run time
ptg10564057 Section 2.2 .3 Constants 43 double sum(const vector<double>&); // sum will not modify its argument (§2.2.5) vector<double> v {1.2, 3.4, 4.5}; // v is not a constant const double s1 = sum(v); // OK: evaluated at run time constexpr double s2 = sum(v); // error: sum(v) not constant expression For a function to be usable in a constant expression, that is, in an expression that will be evaluated by the compiler, it must be defined constexpr. For example: constexpr double square(double x) { return x∗x; } To b e constexpr, a function must be rather simple: just a return-statement computing a value. A constexpr function can be used for non-constant arguments, but when that is done the result is not a constant expression. We allow a constexpr function to be called with non-constant-expression argu- ments in contexts that do not require constant expressions, so that we don’t have to define essen- tially the same function twice: once for constant expressions and once for variables. In a few places, constant expressions are required by language rules (e.g ., array bounds (§2.2 .5, §7.3), case labels (§2.2.4, §9.4 .2), some template arguments (§25.2), and constants declared using constexpr). In other cases, compile-time evaluation is important for performance. Independently of performance issues, the notion of immutability (of an object with an unchangeable state) is an important design concern (§10.4). 2.2.4 Tests and Loops C++ provides a conventional set of statements for expressing selection and looping. For example, here is a simple function that prompts the user and returns a Boolean indicating the response: bool accept() { cout << "Do you want to proceed (y or n)?\n"; // write question char answer = 0; cin >> answer; // read answer if (answer == 'y') return true; return false; } To match the << output operator (‘‘put to’’), the >> operator (‘‘get from’’) is used for input; cin is the standard input stream. The type of the right-hand operand of >> determines what input is accepted, and its right-hand operand is the target of the input operation. The \n character at the end of the output string represents a newline (§2.2 .1). The example could be improved by taking an n (for ‘‘no’’) answer into account: bool accept2() { cout << "Do you want to proceed (y or n)?\n"; // write question char answer = 0; cin >> answer; // read answer
ptg10564057 44 A Tour of C++: The Basics Chapter 2 switch (answer) { case 'y': return true; case 'n': return false; default: cout << "I'll take that for a no.\n"; return false; } } A switch-statement tests a value against a set of constants. The case constants must be distinct, and if the value tested does not match any of them, the default is chosen. If no default is provided, no action is taken if the value doesn’t match any case constant. Few programs are written without loops. For example, we might like to give the user a few tries to produce acceptable input: bool accept3() { int tries = 1; while (tries<4) { cout << "Do you want to proceed (y or n)?\n"; // write question char answer = 0; cin >> answer; // read answer switch (answer) { case 'y': return true; case 'n': return false; default: cout << "Sorry, I don't understand that.\n"; ++tries; // increment } } cout << "I'll take that for a no.\n"; return false; } The while-statement executes until its condition becomes false. 2.2.5 Pointers, Arrays, and Loops An array of elements of type char can be declared like this: char v[6]; // array of 6 characters Similarly, a pointer can be declared like this: char∗ p; // pointer to character In declarations, [] means ‘‘array of ’’ and ∗ means ‘‘pointer to.’’ All arrays have 0 as their lower
ptg10564057 Section 2.2 .5 Pointers, Arrays, and Loops 45 bound, so v has six elements, v[0] to v[5]. The size of an array must be a constant expression (§2.2 .3). A pointer variable can hold the address of an object of the appropriate type: char∗ p = &v[3]; // p points to v’s fourth element charx=∗p; // *p is the object that p points to In an expression, prefix unary ∗ means ‘‘contents of ’’ and prefix unary & means ‘‘address of.’’ We can represent the result of that initialized definition graphically: p: v: 0: 1: 2: 3: 4: 5: Consider copying ten elements from one array to another: void copy_fct() { int v1[10] = {0,1,2,3,4,5,6,7,8,9}; int v2[10]; // to become a copy of v1 for (auto i=0; i!=10; ++i) // copy elements v2[i]=v1[i]; // ... } This for-statement can be read as ‘‘set i to zero; while i is not 10, copy the ith element and increment i.’’ When applied to an integer variable, the increment operator, ++, simply adds 1. C++ also offers a simpler for-statement, called a range-for-statement, for loops that traverse a sequence in the sim- plest way: void print() { int v[] = {0,1,2,3,4,5,6,7,8,9}; for(autox:v) //foreachxinv cout << x << '\n'; for (auto x : {10,21,32,43,54,65}) cout << x << '\n'; // ... } The first range-for-statement can be read as ‘‘for every element of v, from the first to the last, place a copy in x and print it.’’ Note that we don’t have to specify an array bound when we initialize it with a list. The range-for-statement can be used for any sequence of elements (§3.4 .1). If we didn’t want to copy the values from v into the variable x, but rather just have x refer to an element, we could write:
ptg10564057 46 A Tour of C++: The Basics Chapter 2 void increment() { int v[] = {0,1,2,3,4,5,6,7,8,9}; for (auto& x : v) ++x; // ... } In a declaration, the unary suffix & means ‘‘reference to.’’ A reference is similar to a pointer, except that you don’t need to use a prefix ∗ to access the value referred to by the reference. Also, a reference cannot be made to refer to a different object after its initialization. When used in declara- tions, operators (such as &, ∗, and []) are called declarator operators: T a[n]; // T[n]: array of n Ts (§7.3) T∗ p; // T*: pointer to T (§7.2) T& r; // T&: reference to T (§7.7) T f(A); // T(A): function taking an argument of type A returning a result of type T (§2.2 .1) We try to ensure that a pointer always points to an object, so that dereferencing it is valid. When we don’t have an object to point to or if we need to represent the notion of ‘‘no object available’’ (e.g., for an end of a list), we give the pointer the value nullptr (‘‘the null pointer’’). There is only one nullptr shared by all pointer types: double∗ pd = nullptr; Link<Record>∗ lst = nullptr; // pointer to a Link to a Record int x = nullptr; // error: nullptr is a pointer not an integer It is often wise to check that a pointer argument that is supposed to point to something, actually points to something: int count_x(char∗ p, char x) // count the number of occurrences of x in p[] // p is assumed to point to a zero-terminated array of char (or to nothing) { if (p==nullptr) return 0; int count = 0; for (; ∗p!=0; ++p) if (∗p==x) ++count; return count; } Note how we can move a pointer to point to the next element of an array using ++ and that we can leave out the initializer in a for-statement if we don’t need it. The definition of count_x() assumes that the char∗ is a C-style string, that is, that the pointer points to a zero-terminated array of char. In older code, 0 or NULL is typically used instead of nullptr (§7.2 .2). However, using nullptr eliminates potential confusion between integers (such as 0 or NULL) and pointers (such as nullptr).
ptg10564057 Section 2.3 User-Defined Types 47 2.3 User-Defined Types We call the types that can be built from the fundamental types (§2.2 .2), the const modifier (§2.2 .3), and the declarator operators (§2.2 .5) built-in types. C++’s set of built-in types and operations is rich, but deliberately low-level. They directly and efficiently reflect the capabilities of conventional computer hardware. However, they don’t provide the programmer with high-level facilities to con- veniently write advanced applications. Instead, C++ augments the built-in types and operations with a sophisticated set of abstraction mechanisms out of which programmers can build such high- level facilities. The C++ abstraction mechanisms are primarily designed to let programmers design and implement their own types, with suitable representations and operations, and for programmers to simply and elegantly use such types. Types built out of the built-in types using C++’s abstraction mechanisms are called user-defined types. They are referred to as classes and enumerations. Most of this book is devoted to the design, implementation, and use of user-defined types. The rest of this chapter presents the simplest and most fundamental facilities for that. Chapter 3 is a more complete description of the abstraction mechanisms and the programming styles they support. Chapter 4 and Chapter 5 present an overview of the standard library, and since the standard library mainly consists of user-defined types, they provide examples of what can be built using the lan- guage facilities and programming techniques presented in Chapter 2 and Chapter 3. 2.3.1 Structures The first step in building a new type is often to organize the elements it needs into a data structure, a struct: struct Vector { int sz; // number of elements double∗ elem; // pointer to elements }; This first version of Vector consists of an int and a double∗. A variable of type Vector can be defined like this: Vector v; However, by itself that is not of much use because v’s elem pointer doesn’t point to anything. To be useful, we must give v some elements to point to. For example, we can construct a Vector like this: void vector_init(Vector& v, int s) { v.elem = new double[s]; // allocate an array of s doubles v.sz = s; } That is, v’s elem member gets a pointer produced by the new operator and v’s size member gets the number of elements. The & in Vector& indicates that we pass v by non-const reference (§2.2 .5, §7.7); that way, vector_init() can modify the vector passed to it. The new operator allocates memory from an area called the free store (also known as dynamic memory and heap; §11.2).
ptg10564057 48 A Tour of C++: The Basics Chapter 2 A simple use of Vector looks like this: double read_and_sum(int s) // read s integers from cin and return their sum; s is assumed to be positive { Vector v; vector_init(v,s); // allocate s elements for v for (int i=0; i!=s; ++i) cin>>v.elem[i]; // read into elements double sum = 0; for (int i=0; i!=s; ++i) sum+=v.elem[i]; // take the sum of the elements return sum; } There is a long way to go before our Vector is as elegant and flexible as the standard-library vector. In particular, a user of Vector has to know every detail of Vector’s representation. The rest of this chapter and the next gradually improve Vector as an example of language features and techniques. Chapter 4 presents the standard-library vector, which contains many nice improvements, and Chap- ter 31 presents the complete vector in the context of other standard-library facilities. I use vector and other standard-library components as examples • to illustrate language features and design techniques, and • to help you learn and use the standard-library components. Don’t reinvent standard-library components, such as vector and string; use them. We u s e . (dot) to access struct members through a name (and through a reference) and −> to access struct members through a pointer. For example: void f(Vector v, Vector& rv, Vector∗ pv) { int i1 = v.sz; // access through name int i2 = rv.sz; // access through reference int i4 = pv−>sz; // access through pointer } 2.3.2 Classes Having the data specified separately from the operations on it has advantages, such as the ability to use the data in arbitrary ways. However, a tighter connection between the representation and the operations is needed for a user-defined type to have all the properties expected of a ‘‘real type.’’ In particular, we often want to keep the representation inaccessible to users, so as to ease use, guaran- tee consistent use of the data, and allow us to later improve the representation. To do that we have to distinguish between the interface to a type (to be used by all) and its implementation (which has access to the otherwise inaccessible data). The language mechanism for that is called a class.A class is defined to have a set of members, which can be data, function, or type members. The inter- face is defined by the public members of a class, and private members are accessible only through that interface. For example:
ptg10564057 Section 2.3 .2 Classes 49 class Vector { public: Vector(int s) :elem{new double[s]}, sz{s} { } // construct a Vector double& operator[](int i) { return elem[i]; } // element access: subscripting int size() { return sz; } private: double∗ elem; // pointer to the elements int sz; // the number of elements }; Given that, we can define a variable of our new type Vector: Vector v(6); // a Vector with 6 elements We can illustrate a Vector object graphically: 6 Vector: elem: sz: 0: 1: 2: 3: 4: 5: Basically, the Vector object is a ‘‘handle’’ containing a pointer to the elements (elem) plus the num- ber of elements (sz). The number of elements (6 in the example) can vary from Vector object to Vector object, and a Vector object can have a different number of elements at different times (§3.2 .1 .3). However, the Vector object itself is always the same size. This is the basic technique for handling varying amounts of information in C++: a fixed-size handle referring to a variable amount of data ‘‘elsewhere’’ (e.g ., on the free store allocated by new; §11.2). How to design and use such objects is the main topic of Chapter 3. Here, the representation of a Vector (the members elem and sz) is accessible only through the interface provided by the public members: Vector(), operator[](), and size(). The read_and_sum() example from §2.3 .1 simplifies to: double read_and_sum(int s) { Vector v(s); // make a vector of s elements for (int i=0; i!=v.size(); ++i) cin>>v[i]; // read into elements double sum = 0; for (int i=0; i!=v.size(); ++i) sum+=v[i]; // take the sum of the elements return sum; } A ‘‘function’’ with the same name as its class is called a constructor, that is, a function used to con- struct objects of a class. So, the constructor, Ve cto r(), replaces vector_init() from §2.3 .1 . Unlike an ordinary function, a constructor is guaranteed to be used to initialize objects of its class. Thus, defining a constructor eliminates the problem of uninitialized variables for a class.
ptg10564057 50 A Tour of C++: The Basics Chapter 2 Vector(int) defines how objects of type Vector are constructed. In particular, it states that it needs an integer to do that. That integer is used as the number of elements. The constructor initializes the Vector members using a member initializer list: :elem{new double[s]}, sz{s} That is, we first initialize elem with a pointer to s elements of type double obtained from the free store. Then, we initialize sz to s. Access to elements is provided by a subscript function, called operator[]. It returns a reference to the appropriate element (a double&). The size() function is supplied to give users the number of elements. Obviously, error handling is completely missing, but we’ll return to that in §2.4 .3. Similarly, we did not provide a mechanism to ‘‘give back’’ the array of doubles acquired by new; §3.2 .1 .2 shows how to use a destructor to elegantly do that. 2.3.3 Enumerations In addition to classes, C++ supports a simple form of user-defined type for which we can enumer- ate the values: enum class Color { red, blue, green }; enum class Traffic_light { green, yellow, red }; Color col = Color::red; Traffic_light light = Traffic_light::red; Note that enumerators (e.g ., red) are in the scope of their enum class, so that they can be used repeatedly in different enum classes without confusion. For example, Color::red is Color’s red which is different from Traffic_light::red. Enumerations are used to represent small sets of integer values. They are used to make code more readable and less error-prone than it would have been had the symbolic (and mnemonic) enu- merator names not been used. The class after the enum specifies that an enumeration is strongly typed and that its enumerators are scoped. Being separate types, enum classes help prevent accidental misuses of constants. In particular, we cannot mix Traffic_light and Color values: Color x = red; // error: which red? Color y = Traffic_light::red; // error: that red is not a Color Color z = Color::red; // OK Similarly, we cannot implicitly mix Color and integer values: int i = Color::red; // error: Color::red is not an int Colorc=2; // error: 2 is not a Color If you don’t want to explicitly qualify enumerator names and want enumerator values to be ints (without the need for an explicit conversion), you can remove the class from enum class to get a ‘‘plain enum’’ (§8.4 .2). By default, an enum class has only assignment, initialization, and comparisons (e.g ., == and <; §2.2 .2) defined. However, an enumeration is a user-defined type so we can define operators for it:
ptg10564057 Section 2.3 .3 Enumerations 51 Traffic_light& operator++(Traffic_light& t) // prefix increment: ++ { switch (t) { case Traffic_light::green: return t=Traffic_light::yellow; case Traffic_light::yellow: return t=Traffic_light::red; case Traffic_light::red: return t=Traffic_light::green; } } Traffic_light next = ++light; // next becomes Traffic_light::green C++ also offers a less strongly typed ‘‘plain’’ enum (§8.4 .2). 2.4 Modularity A C++ program consists of many separately developed parts, such as functions (§2.2 .1, Chapter 12), user-defined types (§2.3, §3.2, Chapter 16), class hierarchies (§3.2 .4, Chapter 20), and tem- plates (§3.4, Chapter 23). The key to managing this is to clearly define the interactions among those parts. The first and most important step is to distinguish between the interface to a part and its implementation. At the language level, C++ represents interfaces by declarations. A declara- tion specifies all that’s needed to use a function or a type. For example: double sqrt(double); // the square root function takes a double and returns a double class Vector { public: Vector(int s); double& operator[](int i); int size(); private: double∗ elem; // elem points to an array of sz doubles int sz; }; The key point here is that the function bodies, the function definitions, are ‘‘elsewhere.’’ For this example, we might like for the representation of Vector to be ‘‘elsewhere’’ also, but we will deal with that later (abstract types; §3.2.2). The definition of sqrt() will look like this: double sqrt(double d) // definition of sqrt() { // ... algorithm as found in math textbook ... } For Vector, we need to define all three member functions: Vector::Vector(int s) // definition of the constructor :elem{new double[s]}, sz{s} // initialize members { }
ptg10564057 52 A Tour of C++: The Basics Chapter 2 double& Vector::operator[](int i) // definition of subscripting { return elem[i]; } int Vector::size() // definition of size() { return sz; } We must define Vector’s functions, but not sqrt() because it is part of the standard library. However, that makes no real difference: a library is simply some ‘‘other code we happen to use’’ written with the same language facilities as we use. 2.4.1 Separate Compilation C++ supports a notion of separate compilation where user code sees only declarations of types and functions used. The definitions of those types and functions are in separate source files and com- piled separately. This can be used to organize a program into a set of semi-independent code frag- ments. Such separation can be used to minimize compilation times and to strictly enforce separa- tion of logically distinct parts of a program (thus minimizing the chance of errors). A library is often a separately compiled code fragments (e.g., functions). Typically, we place the declarations that specify the interface to a module in a file with a name indicating its intended use. For example: // Vector.h: class Vector { public: Vector(int s); double& operator[](int i); int size(); private: double∗ elem; // elem points to an array of sz doubles int sz; }; This declaration would be placed in a file Vector.h, and users will include that file, called a header file, to access that interface. For example: // user.cpp: #include "Vector.h" // get Vector’s interface #include <cmath> // get the the standard-library math function interface including sqrt() using namespace std; // make std members visible (§2.4 .2)
ptg10564057 Section 2.4 .1 Separate Compilation 53 double sqrt_sum(Vector& v) { double sum = 0; for (int i=0; i!=v.size(); ++i) sum+=sqrt(v[i]); // sum of square roots return sum; } To help the compiler ensure consistency, the .cpp file providing the implementation of Vector will also include the .h file providing its interface: // Vector.cpp: #include "Vector.h" // get the interface Vector::Vector(int s) :elem{new double[s]}, sz{s} { } double& Vector::operator[](int i) { return elem[i]; } int Vector::size() { return sz; } The code in user.cpp and Vector.cpp shares the Vector interface information presented in Vector.h, but the two files are otherwise independent and can be separately compiled. Graphically, the pro- gram fragments can be represented like this: Vector interface #include "Vector.h" use Vector #include "Vector.h" define Vector Vector.h: user.cpp: Vector.cpp: Strictly speaking, using separate compilation isn’t a language issue; it is an issue of how best to take advantage of a particular language implementation. However, it is of great practical impor- tance. The best approach is to maximize modularity, represent that modularity logically through language features, and then exploit the modularity physically through files for effective separate compilation (Chapter 14, Chapter 15).
ptg10564057 54 A Tour of C++: The Basics Chapter 2 2.4.2 Namespaces In addition to functions (§2.2 .1, Chapter 12), classes (Chapter 16), and enumerations (§2.3 .3, §8.4), C++ offers namespaces (Chapter 14) as a mechanism for expressing that some declarations belong together and that their names shouldn’t clash with other names. For example, I might want to experiment with my own complex number type (§3.2 .1 .1, §18.3, §40.4): namespace My_code { class complex { /* ... */ }; complex sqrt(complex); // ... int main(); } int My_code::main() { complex z {1,2}; auto z2 = sqrt(z); std::cout << '{' << z2.real() << ',' << z2.imag() << "}\n"; // ... }; int main() { return My_code::main(); } By putting my code into the namespace My_code, I make sure that my names do not conflict with the standard-library names in namespace std (§4.1 .2). The precaution is wise, because the standard library does provide support for complex arithmetic (§3.2 .1 .1, §40.4). The simplest way to access a name in another namespace is to qualify it with the namespace name (e.g ., std::cout and My_code::main). The ‘‘real main()’’ is defined in the global namespace, that is, not local to a defined namespace, class, or function. To gain access to names in the stan- dard-library namespace, we can use a using-directive (§14.2 .3): using namespace std; Namespaces are primarily used to organize larger program components, such as libraries. They simplify the composition of a program out of separately developed parts. 2.4.3 Error Handling Error handling is a large and complex topic with concerns and ramifications that go far beyond lan- guage facilities into programming techniques and tools. However, C++ provides a few features to help. The major tool is the type system itself. Instead of painstakingly building up our applications from the built-in types (e.g ., char, int, and double) and statements (e.g ., if, while, and for), we build more types that are appropriate for our applications (e.g ., string, map, and regex) and algorithms (e.g., sort(), find_if(), and draw_all()). Such higher level constructs simplify our programming, limit our opportunities for mistakes (e.g ., you are unlikely to try to apply a tree traversal to a dialog box),
ptg10564057 Section 2.4 .3 Error Handling 55 and increase the compiler’s chances of catching such errors. The majority of C++ constructs are dedicated to the design and implementation of elegant and efficient abstractions (e.g ., user-defined types and algorithms using them). One effect of this modularity and abstraction (in particular, the use of libraries) is that the point where a run-time error can be detected is separated from the point where it can be handled. As programs grow, and especially when libraries are used extensively, standards for handling errors become important. 2.4 .3.1 Exceptions Consider again the Vector example. What ought to be done when we try to access an element that is out of range for the vector from §2.3.2? • The writer of Vector doesn’t know what the user would like to have done in this case (the writer of Vector typically doesn’t even know in which program the vector will be running). • The user of Vector cannot consistently detect the problem (if the user could, the out-of-range access wouldn’t happen in the first place). The solution is for the Vector implementer to detect the attempted out-of-range access and then tell the user about it. The user can then take appropriate action. For example, Vector::operator[]() can detect an attempted out-of-range access and throw an out_of_range exception: double& Vector::operator[](int i) { if (i<0 || size()<=i) throw out_of_range{"Vector::operator[]"}; return elem[i]; } The throw transfers control to a handler for exceptions of type out_of_range in some function that directly or indirectly called Vector::operator[](). To do that, the implementation will unwind the function call stack as needed to get back to the context of that caller (§13.5 .1). For example: void f(Vector& v) { // ... try { // exceptions here are handled by the handler defined below v[v.size()]=7; //try to access beyond the end of v } catch (out_of_range) { // oops: out_of_range error // ... handle range error ... } // ... } We put code for which we are interested in handling exceptions into a try-block. That attempted assignment to v[v.size()] will fail. Therefore, the catch-clause providing a handler for out_of_range will be entered. The out_of_range type is defined in the standard library and is in fact used by some standard-library container access functions. Use of the exception-handling mechanisms can make error handling simpler, more systematic, and more readable. See Chapter 13 for further discussion, details, and examples.
ptg10564057 56 A Tour of C++: The Basics Chapter 2 2.4 .3.2 Invariants The use of exceptions to signal out-of-range access is an example of a function checking its argu- ment and refusing to act because a basic assumption, a precondition, didn’t hold. Had we formally specified Vector’s subscript operator, we would have said something like ‘‘the index must be in the [0:size()) range,’’ and that was in fact what we tested in our operator[](). Whenever we define a function, we should consider what its preconditions are and if feasible test them (see §12.4, §13.4). However, operator[]() operates on objects of type Vector and nothing it does makes any sense unless the members of Vector have ‘‘reasonable’’ values. In particular, we did say ‘‘elem points to an array of sz doubles’’ but we only said that in a comment. Such a statement of what is assumed to be true for a class is called a class invariant, or simply an invariant. It is the job of a constructor to establish the invariant for its class (so that the member functions can rely on it) and for the mem- ber functions to make sure that the invariant holds when they exit. Unfortunately, our Vector con- structor only partially did its job. It properly initialized the Vector members, but it failed to check that the arguments passed to it made sense. Consider: Vector v(−27); This is likely to cause chaos. Here is a more appropriate definition: Vector::Vector(int s) { if (s<0) throw length_error{}; elem = new double[s]; sz=s; } I use the standard-library exception length_error to report a non-positive number of elements because some standard-library operations use that exception to report problems of this kind. If operator new can’t find memory to allocate, it throws a std::bad_alloc. We can now write: void test() { try { Vector v(−27); } catch (std::length_error) { // handle negative size } catch (std::bad_alloc) { // handle memory exhaustion } } You can define your own classes to be used as exceptions and have them carry arbitrary information from a point where an error is detected to a point where it can be handled (§13.5). Often, a function has no way of completing its assigned task after an exception is thrown. Then, ‘‘handling’’ an exception simply means doing some minimal local cleanup and rethrowing the exception (§13.5 .2 .1).
ptg10564057 Section 2.4 .3 .2 Invariants 57 The notion of invariants is central to the design of classes, and preconditions serve a similar role in the design of functions. Invariants • helps us to understand precisely what we want • forces us to be specific; that gives us a better chance of getting our code correct (after debugging and testing). The notion of invariants underlies C++’s notions of resource management supported by construc- tors (§2.3 .2) and destructors (§3.2 .1 .2, §5.2). See also §13.4, §16.3 .1, and §17.2 . 2.4 .3.3 Static Assertions Exceptions report errors found at run time. If an error can be found at compile time, it is usually preferable to do so. That’s what much of the type system and the facilities for specifying the inter- faces to user-defined types are for. However, we can also perform simple checks on other proper- ties that are known at compile time and report failures as compiler error messages. For example: static_assert(4<=sizeof(int), "integers are too small"); // check integer size This will write integers are too small if 4<=sizeof(int) does not hold, that is, if an int on this system does not have at least 4 bytes. We call such statements of expectations assertions. The static_assert mechanism can be used for anything that can be expressed in terms of constant expressions (§2.2 .3, §10.4). For example: constexpr double C = 299792.458; // km/s void f(double speed) { const double local_max = 160.0/(60∗60); // 160 km/h == 160.0/(60*60) km/s static_assert(speed<C,"can't go that fast"); // error: speed must be a constant static_assert(local_max<C,"can't go that fast"); // OK // ... } In general, static_assert(A,S) prints S as a compiler error message if A is not true. The most important uses of static_assert come when we make assertions about types used as parameters in generic programming (§5.4 .2, §24.3). For runtime-checked assertions, see §13.4 . 2.5 Postscript The topics covered in this chapter roughly correspond to the contents of Part II (Chapters 6–15). Those are the parts of C++ that underlie all programming techniques and styles supported by C++. Experienced C and C++ programmers, please note that this foundation does not closely correspond to the C or C++98 subsets of C++ (that is, C++11).
ptg10564057 58 A Tour of C++: The Basics Chapter 2 2.6 Advice [1] Don’t panic! All will become clear in time; §2.1 . [2] You don’t have to know every detail of C++ to write good programs; §1.3 .1. [3] Focus on programming techniques, not on language features; §2.1 .
ptg10564057 3 A Tour of C++: Abstraction Mechanisms Don’t Panic! – Douglas Adams • Introduction • Classes Concrete Types; Abstract Types; Virtual Functions; Class Hierarchies • Copy and Move Copying Containers; Moving Containers; Resource Management; Suppressing Operations • Templates Parameterized Types; Function Templates; Function Objects; Variadic Templates; Aliases • Advice 3.1 Introduction This chapter aims to give you an idea of C++’s support for abstraction and resource management without going into a lot of detail. It informally presents ways of defining and using new types (user-defined types). In particular, it presents the basic properties, implementation techniques, and language facilities used for concrete classes, abstract classes, and class hierarchies. Templates are introduced as a mechanism for parameterizing types and algorithms with (other) types and algo- rithms. Computations on user-defined and built-in types are represented as functions, sometimes generalized to template functions and function objects. These are the language facilities supporting the programming styles known as object-oriented programming and generic programming. The next two chapters follow up by presenting examples of standard-library facilities and their use. The assumption is that you have programmed before. If not, please consider reading a text- book, such as Programming: Principles and Practice Using C++ [Stroustrup,2009], before contin- uing here. Even if you have programmed before, the language you used or the applications you wrote may be very different from the style of C++ presented here. If you find this ‘‘lightning tour’’ confusing, skip to the more systematic presentation starting in Chapter 6.
ptg10564057 60 A Tour of C++: Abstraction Mechanisms Chapter 3 As in Chapter 2, this tour presents C++ as an integrated whole, rather than as a layer cake. Consequently, it does not identify language features as present in C, part of C++98, or new in C++11. Such historical information can be found in §1.4 and Chapter 44. 3.2 Classes The central language feature of C++ is the class. A class is a user-defined type provided to repre- sent a concept in the code of a program. Whenever our design for a program has a useful concept, idea, entity, etc., we try to represent it as a class in the program so that the idea is there in the code, rather than just in our head, in a design document, or in some comments. A program built out of a well chosen set of classes is far easier to understand and get right than one that builds everything directly in terms of the built-in types. In particular, classes are often what libraries offer. Essentially all language facilities beyond the fundamental types, operators, and statements exist to help define better classes or to use them more conveniently. By ‘‘better,’’ I mean more correct, easier to maintain, more efficient, more elegant, easier to use, easier to read, and easier to reason about. Most programming techniques rely on the design and implementation of specific kinds of classes. The needs and tastes of programmers vary immensely. Consequently, the support for classes is extensive. Here, we will just consider the basic support for three important kinds of classes: • Concrete classes (§3.2 .1) • Abstract classes (§3.2 .2) • Classes in class hierarchies (§3.2.4) An astounding number of useful classes turn out to be of these three kinds. Even more classes can be seen as simple variants of these kinds or are implemented using combinations of the techniques used for these. 3.2.1 Concrete Types The basic idea of concrete classes is that they behave ‘‘just like built-in types.’’ For example, a complex number type and an infinite-precision integer are much like built-in int, except of course that they have their own semantics and sets of operations. Similarly, a vector and a string are much like built-in arrays, except that they are better behaved (§4.2, §4.3 .2, §4.4 .1). The defining characteristic of a concrete type is that its representation is part of its definition. In many important cases, such as a vector, that representation is only one or more pointers to more data stored elsewhere, but it is present in each object of a concrete class. That allows implementa- tions to be optimally efficient in time and space. In particular, it allows us to • place objects of concrete types on the stack, in statically allocated memory, and in other objects (§6.4 .2); • refer to objects directly (and not just through pointers or references); • initialize objects immediately and completely (e.g ., using constructors; §2.3 .2); and • copy objects (§3.3). The representation can be private (as it is for Vector; §2.3 .2) and accessible only through the mem- ber functions, but it is present. Therefore, if the representation changes in any significant way, a user must recompile. This is the price to pay for having concrete types behave exactly like built-in
ptg10564057 Section 3.2 .1 Concrete Types 61 types. For types that don’t change often, and where local variables provide much-needed clarity and efficiency, this is acceptable and often ideal. To increase flexibility, a concrete type can keep major parts of its representation on the free store (dynamic memory, heap) and access them through the part stored in the class object itself. That’s the way vector and string are implemented; they can be considered resource handles with carefully crafted interfaces. 3.2 .1.1 An Arithmetic Type The ‘‘classical user-defined arithmetic type’’ is complex: class complex { double re, im; // representation: two doubles public: complex(double r, double i) :re{r}, im{i} {} // construct complex from two scalars complex(double r) :re{r}, im{0} {} // construct complex from one scalar complex() :re{0}, im{0} {} // default complex: {0,0} double real() const { return re; } void real(double d) { re=d; } double imag() const { return im; } void imag(double d) { im=d; } complex& operator+=(complex z) { re+=z.re, im+=z.im; return ∗this; } // add to re and im // and return the result complex& operator−=(complex z) { re−=z.re,im−=z.im; return ∗this; } complex& operator∗=(complex); // defined out-of-class somewhere complex& operator/=(complex); // defined out-of-class somewhere }; This is a slightly simplified version of the standard-library complex (§40.4). The class definition itself contains only the operations requiring access to the representation. The representation is sim- ple and conventional. For practical reasons, it has to be compatible with what Fortran provided 50 years ago, and we need a conventional set of operators. In addition to the logical demands, complex must be efficient or it will remain unused. This implies that simple operations must be inlined. That is, simple operations (such as constructors, +=, and imag()) must be implemented without func- tion calls in the generated machine code. Functions defined in a class are inlined by default. An industrial-strength complex (like the standard-library one) is carefully implemented to do appropri- ate inlining. A constructor that can be invoked without an argument is called a default constructor. Thus, complex() is complex’s default constructor. By defining a default constructor you eliminate the pos- sibility of uninitialized variables of that type. The const specifiers on the functions returning the real and imaginary parts indicate that these functions do not modify the object for which they are called. Many useful operations do not require direct access to the representation of complex, so they can be defined separately from the class definition:
ptg10564057 62 A Tour of C++: Abstraction Mechanisms Chapter 3 complex operator+(complex a, complex b) { return a+=b; } complex operator−(complex a, complex b) { return a−=b; } complex operator−(complex a) { return {−a.real(), −a .imag()}; } // unary minus complex operator∗(complex a, complex b) { return a∗=b; } complex operator/(complex a, complex b) { return a/=b; } Here, I use the fact that an argument passed by value is copied, so that I can modify an argument without affecting the caller’s copy, and use the result as the return value. The definitions of == and != are straightforward: bool operator==(complex a, complex b) // equal { return a.real()==b.real() && a.imag()==b.imag(); } bool operator!=(complex a, complex b) // not equal { return !(a==b); } complex sqrt(complex); // ... Class complex can be used like this: void f(complex z) { complex a {2.3}; // construct {2.3,0.0} from 2.3 complex b {1/a}; complex c {a+z∗complex{1,2.3}}; // ... if(c!=b) c=−(b/a)+2∗b; } The compiler converts operators involving complex numbers into appropriate function calls. For example, c!=b means operator!=(c,b) and 1/a means operator/(complex{1},a). User-defined operators (‘‘overloaded operators’’) should be used cautiously and conventionally. The syntax is fixed by the language, so you can’t define a unary /. Also, it is not possible to change the meaning of an operator for built-in types, so you can’t redefine + to subtract ints. 3.2 .1.2 A Container A container is an object holding a collection of elements, so we call Vector a container because it is the type of objects that are containers. As defined in §2.3 .2, Vector isn’t an unreasonable container of doubles: it is simple to understand, establishes a useful invariant (§2.4 .3 .2), provides range- checked access (§2.4 .3 .1), and provides size() to allow us to iterate over its elements. However, it does have a fatal flaw: it allocates elements using new but never deallocates them. That’s not a good idea because although C++ defines an interface for a garbage collector (§34.5), it is not
ptg10564057 Section 3.2 .1 .2 A Container 63 guaranteed that one is available to make unused memory available for new objects. In some envi- ronments you can’t use a collector, and sometimes you prefer more precise control of destruction (§13.6.4) for logical or performance reasons. We need a mechanism to ensure that the memory allocated by the constructor is deallocated; that mechanism is a destructor: class Vector { private: double∗ elem; // elem points to an array of sz doubles int sz; public: Vector(int s) :elem{new double[s]}, sz{s} // constructor: acquire resources { for (int i=0; i!=s; ++i) elem[i]=0; // initialize elements } ̃Vector() { delete[] elem; } // destructor: release resources double& operator[](int i); int size() const; }; The name of a destructor is the complement operator, ̃, followed by the name of the class; it is the complement of a constructor. Vector’s constructor allocates some memory on the free store (also called the heap or dynamic store) using the new operator. The destructor cleans up by freeing that memory using the delete operator. This is all done without intervention by users of Vector. The users simply create and use Vectors much as they would variables of built-in types. For example: void fct(int n) { Vector v(n); //...usev... { Vector v2(2∗n); //...usevandv2... }//v2 is destroyed here //...usev.. }//v is destroyed here Vector obeys the same rules for naming, scope, allocation, lifetime, etc., as does a built-in type, such as int and char. For details on how to control the lifetime of an object, see §6.4 . This Vector has been simplified by leaving out error handling; see §2.4 .3 . The constructor/destructor combination is the basis of many elegant techniques. In particular, it is the basis for most C++ general resource management techniques (§5.2, §13.3). Consider a graphical illustration of a Vector:
ptg10564057 64 A Tour of C++: Abstraction Mechanisms Chapter 3 6 Vector: elem: sz: 0 0 0 0 0 0 0: 1: 2: 3: 4: 5: The constructor allocates the elements and initializes the Vector members appropriately. The de- structor deallocates the elements. This handle-to-data model is very commonly used to manage data that can vary in size during the lifetime of an object. The technique of acquiring resources in a constructor and releasing them in a destructor, known as Resource Acquisition Is Initialization or RAII, allows us to eliminate ‘‘naked new operations,’’ that is, to avoid allocations in general code and keep them buried inside the implementation of well-behaved abstractions. Similarly, ‘‘naked delete operations’’ should be avoided. Avoiding naked new and naked delete makes code far less error-prone and far easier to keep free of resource leaks (§5.2). 3.2 .1.3 Initializing Containers A container exists to hold elements, so obviously we need convenient ways of getting elements into a container. We can handle that by creating a Vec tor with an appropriate number of elements and then assigning to them, but typically other ways are more elegant. Here, I just mention two favorites: • Initializer-list constructor: Initialize with a list of elements. • push_back(): Add a new element at the end (at the back of) the sequence. These can be declared like this: class Vector { public: Vector(std::initializer_list<double>); // initialize with a list // ... void push_back(double); // add element at end increasing the size by one // ... }; The push_back() is useful for input of arbitrary numbers of elements. For example: Vector read(istream& is) { Vector v; for (double d; is>>d;) // read floating-point values into d v.push_back(d); //adddtov return v; } The input loop is terminated by an end-of-file or a formatting error. Until that happens, each num- ber read is added to the Vector so that at the end, v’s size is the number of elements read. I used a for-statement rather than the more conventional while-statement to keep the scope of d limited to the loop. The implementation of push_back() is discussed in §13.6 .4 .3 . The way to provide Vector with a move constructor, so that returning a potentially huge amount of data from read() is cheap, is explained in §3.3.2 .
ptg10564057 Section 3.2 .1 .3 Initializing Containers 65 The std::initializer_list used to define the initializer-list constructor is a standard-library type known to the compiler: when we use a {}-list, such as {1,2,3,4}, the compiler will create an object of type initializer_list to give to the program. So, we can write: Vector v1 = {1,2,3,4,5}; // v1 has 5 elements Vector v2 = {1.23, 3.45, 6.7, 8}; // v2 has 4 elements Vector’s initializer-list constructor might be defined like this: Vector::Vector(std::initializer_list<double> lst) // initialize with a list :elem{new double[lst.size()]}, sz{lst.size()} { copy(lst.begin(),lst.end(),elem); // copy from lst into elem } 3.2.2 Abstract Types Types such as complex and Vector are called concrete types because their representation is part of their definition. In that, they resemble built-in types. In contrast, an abstract type is a type that completely insulates a user from implementation details. To do that, we decouple the interface from the representation and give up genuine local variables. Since we don’t know anything about the representation of an abstract type (not even its size), we must allocate objects on the free store (§3.2 .1 .2, §11.2) and access them through references or pointers (§2.2.5, §7.2, §7.7). First, we define the interface of a class Container which we will design as a more abstract ver- sion of our Vector: class Container { public: virtual double& operator[](int) = 0; // pure virtual function virtual int size() const = 0; // const member function (§3.2 .1 .1) virtual ̃Container() {} // destructor (§3.2 .1.2) }; This class is a pure interface to specific containers defined later. The word virtual means ‘‘may be redefined later in a class derived from this one.’’ Unsurprisingly, a function declared virtual is called a virtual function. A class derived from Container provides an implementation for the Con- tainer interface. The curious =0 syntax says the function is pure virtual; that is, some class derived from Container must define the function. Thus, it is not possible to define an object that is just a Container;aContainer can only serve as the interface to a class that implements its operator[]() and size() functions. A class with a pure virtual function is called an abstract class. This Container can be used like this: void use(Container& c) { const int sz = c.size(); for (int i=0; i!=sz; ++i) cout << c[i] << '\n'; }
ptg10564057 66 A Tour of C++: Abstraction Mechanisms Chapter 3 Note how use() uses the Container interface in complete ignorance of implementation details. It uses size() and [] without any idea of exactly which type provides their implementation. A class that provides the interface to a variety of other classes is often called a polymorphic type (§20.3 .2). As is common for abstract classes, Container does not have a constructor. After all, it does not have any data to initialize. On the other hand, Container does have a destructor and that destructor is virtual. Again, that is common for abstract classes because they tend to be manipulated through references or pointers, and someone destroying a Container through a pointer has no idea what resources are owned by its implementation; see also §3.2 .4 . A container that implements the functions required by the interface defined by the abstract class Container could use the concrete class Vector: class Vector_container : public Container { // Vector_container implements Container Vector v; public: Vector_container(int s) : v(s) { } // Vector of s elements ̃Vector_container() {} double& operator[](int i) { return v[i]; } int size() const { return v.size(); } }; The :public can be read as ‘‘is derived from’’ or ‘‘is a subtype of.’’ Class Vector_container is said to be derived from class Container, and class Container is said to be a base of class Vector_container. An alternative terminology calls Vector_container and Container subclass and superclass, respec- tively. The derived class is said to inherit members from its base class, so the use of base and derived classes is commonly referred to as inheritance. The members operator[]() and size() are said to override the corresponding members in the base class Container (§20.3 .2). The destructor (̃Vector_container()) overrides the base class destructor (̃Container()). Note that the member destructor (̃Vector()) is implicitly invoked by its class’s de- structor (̃Vector_container()). For a function like use(Container&) to use a Container in complete ignorance of implementation details, some other function will have to make an object on which it can operate. For example: void g() { Vector_container vc {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; use(vc); } Since use() doesn’t know about Vector_containers but only knows the Container interface, it will work just as well for a different implementation of a Container. For example: class List_container : public Container { // List_container implements Container std::list<double> ld; // (standard-library) list of doubles (§4.4 .2) public: List_container() { } // empty List List_container(initializer_list<double> il) : ld{il} { } ̃List_container() {}
ptg10564057 Section 3.2 .2 Abstract Types 67 double& operator[](int i); int size() const { return ld.size(); } }; double& List_container::operator[](int i) { for(auto&x:ld){ if (i==0) return x; −− i; } throw out_of_range("List container"); } Here, the representation is a standard-library list<double>. Usually, I would not implement a con- tainer with a subscript operation using a list, because performance of list subscripting is atrocious compared to vector subscripting. However, here I just wanted to show an implementation that is radically different from the usual one. A function can create a List_container and have use() use it: void h() { List_containerlc={1,2,3,4,5,6,7,8,9}; use(lc); } The point is that use(Container&) has no idea if its argument is a Vector_container,aList_container, or some other kind of container; it doesn’t need to know. It can use any kind of Container. It knows only the interface defined by Container. Consequently, use(Container&) needn’t be recompiled if the implementation of List_container changes or a brand-new class derived from Container is used. The flip side of this flexibility is that objects must be manipulated through pointers or references (§3.3, §20.4). 3.2.3 Virtual Functions Consider again the use of Container: void use(Container& c) { const int sz = c.size(); for (int i=0; i!=sz; ++i) cout << c[i] << '\n'; } How is the call c[i] in use() resolved to the right operator[]()? When h() calls use(), List_container’s operator[]() must be called. When g() calls use(), Vector_container’s operator[]() must be called. To achieve this resolution, a Container object must contain information to allow it to select the right function to call at run time. The usual implementation technique is for the compiler to convert the name of a virtual function into an index into a table of pointers to functions. That table is usually
ptg10564057 68 A Tour of C++: Abstraction Mechanisms Chapter 3 called the virtual function table or simply the vtbl. Each class with virtual functions has its own vtbl identifying its virtual functions. This can be represented graphically like this: v Vector_container::operator[]() Vector_container::size() Vector_container::̃Vector_container() vtbl: Vector_container: ld List_container::operator[]() List_container::size() List_container::̃List_container() vtbl: List_container: The functions in the vtbl allow the object to be used correctly even when the size of the object and the layout of its data are unknown to the caller. The implementation of the caller needs only to know the location of the pointer to the vtbl in a Container and the index used for each virtual func- tion. This virtual call mechanism can be made almost as efficient as the ‘‘normal function call’’ mechanism (within 25%). Its space overhead is one pointer in each object of a class with virtual functions plus one vtbl for each such class. 3.2.4 Class Hierarchies The Container example is a very simple example of a class hierarchy. A class hierarchy is a set of classes ordered in a lattice created by derivation (e.g ., : public). We use class hierarchies to rep- resent concepts that have hierarchical relationships, such as ‘‘A fire engine is a kind of a truck which is a kind of a vehicle’’ and ‘‘A smiley face is a kind of a circle which is a kind of a shape.’’ Huge hierarchies, with hundreds of classes, that are both deep and wide are common. As a semi- realistic classic example, let’s consider shapes on a screen: Shape Circle Triangle Smiley The arrows represent inheritance relationships. For example, class Circle is derived from class Shape. To represent that simple diagram in code, we must first specify a class that defines the gen- eral properties of all shapes:
ptg10564057 Section 3.2 .4 Class Hierarchies 69 class Shape { public: virtual Point center() const =0; // pure virtual virtual void move(Point to) =0; virtual void draw() const = 0; // draw on current "Canvas" virtual void rotate(int angle) = 0; virtual ̃Shape() {} // destructor // ... }; Naturally, this interface is an abstract class: as far as representation is concerned, nothing (except the location of the pointer to the vtbl) is common for every Shape. Given this definition, we can write general functions manipulating vectors of pointers to shapes: void rotate_all(vector<Shape∗>& v, int angle) // rotate v’s elements by angle degrees { for(autop:v) p−>rotate(angle); } To define a particular shape, we must say that it is a Shape and specify its particular properties (including its virtual functions): class Circle : public Shape { public: Circle(Point p, int rr); // constructor Point center() const { return x; } void move(Point to) { x=to; } void draw() const; void rotate(int) {} // nice simple algorithm private: Point x; // center int r; // radius }; So far, the Shape and Circle example provides nothing new compared to the Container and Vector_container example, but we can build further: class Smiley : public Circle { // use the circle as the base for a face public: Smiley(Point p, int r) : Circle{p,r}, mouth{nullptr} { } ̃Smiley() { delete mouth; for (auto p : eyes) delete p; }
ptg10564057 70 A Tour of C++: Abstraction Mechanisms Chapter 3 void move(Point to); void draw() const; void rotate(int); void add_eye(Shape∗ s) { eyes.push_back(s); } void set_mouth(Shape∗ s); virtual void wink(int i); // wink eye number i // ... private: vector<Shape∗> eyes; // usually two eyes Shape∗ mouth; }; The push_back() member function adds its argument to the vector (here, eyes), increasing that vector’s size by one. We can now define Smiley::draw() using calls to Smiley’s base and member draw()s: void Smiley::draw() { Circle::draw(); for (auto p : eyes) p−>draw(); mouth−>draw(); } Note the way that Smiley keeps its eyes in a standard-library vector and deletes them in its de- structor. Shape’s destructor is virtual and Smiley’s destructor overrides it. A virtual destructor is essential for an abstract class because an object of a derived class is usually manipulated through the interface provided by its abstract base class. In particular, it may be deleted through a pointer to a base class. Then, the virtual function call mechanism ensures that the proper destructor is called. That destructor then implicitly invokes the destructors of its bases and members. In this simplified example, it is the programmer’s task to place the eyes and mouth appropri- ately within the circle representing the face. We can add data members, operations, or both as we define a new class by derivation. This gives great flexibility with corresponding opportunities for confusion and poor design. See Chapter 21. A class hierarchy offers two kinds of benefits: • Interface inheritance: An object of a derived class can be used wherever an object of a base class is required. That is, the base class acts as an interface for the derived class. The Con- tainer and Shape classes are examples. Such classes are often abstract classes. • Implementation inheritance: A base class provides functions or data that simplifies the implementation of derived classes. Smiley’s uses of Circle’s constructor and of Circle::draw() are examples. Such base classes often have data members and constructors. Concrete classes – especially classes with small representations – are much like built-in types: we define them as local variables, access them using their names, copy them around, etc. Classes in class hierarchies are different: we tend to allocate them on the free store using new, and we access
ptg10564057 Section 3.2 .4 Class Hierarchies 71 them through pointers or references. For example, consider a function that reads data describing shapes from an input stream and constructs the appropriate Shape objects: enum class Kind { circle, triangle, smiley }; Shape∗ read_shape(istream& is) // read shape descriptions from input stream is { // ... read shape header from is and find its Kind k ... switch (k) { case Kind::circle: // read circle data {Point,int} into p and r return new Circle{p,r}; case Kind::triangle: // read triangle data {Point,Point,Point} into p1, p2, and p3 return new Triangle{p1,p2,p3}; case Kind::smiley: // read smiley data {Point,int,Shape,Shape,Shape} into p, r, e1 ,e2, and m Smiley∗ ps = new Smiley{p,r}; ps−>add_eye(e1); ps−>add_eye(e2); ps−>set_mouth(m); return ps; } } A program may use that shape reader like this: void user() { std::vector<Shape∗>v; while (cin) v.push_back(read_shape(cin)); draw_all(v); // call draw() for each element rotate_all(v,45); // call rotate(45) for each element for (auto p : v) delete p; // remember to delete elements } Obviously, the example is simplified – especially with respect to error handling – but it vividly illustrates that user() has absolutely no idea of which kinds of shapes it manipulates. The user() code can be compiled once and later used for new Shapes added to the program. Note that there are no pointers to the shapes outside user(),souser() is responsible for deallocating them. This is done with the delete operator and relies critically on Shape’s virtual destructor. Because that destructor is virtual, delete invokes the destructor for the most derived class. This is crucial because a derived class may have acquired all kinds of resources (such as file handles, locks, and output streams) that need to be released. In this case, a Smiley deletes its eyes and mouth objects. Experienced programmers will notice that I left open two obvious opportunities for mistakes: • A user might fail to delete the pointer returned by read_shape(). • The owner of a container of Shape pointers might not delete the objects pointed to. In that sense, functions returning a pointer to an object allocated on the free store are dangerous.
ptg10564057 72 A Tour of C++: Abstraction Mechanisms Chapter 3 One solution to both problems is to return a standard-library unique_ptr (§5.2 .1) rather than a ‘‘naked pointer’’ and store unique_ptrs in the container: unique_ptr<Shape> read_shape(istream& is) // read shape descriptions from input stream is { // read shape header from is and find its Kind k switch (k) { case Kind::circle: // read circle data {Point,int} into p and r return unique_ptr<Shape>{new Circle{p,r}}; // §5.2.1 // ... } void user() { vector<unique_ptr<Shape>> v; while (cin) v.push_back(read_shape(cin)); draw_all(v); // call draw() for each element rotate_all(v,45); // call rotate(45) for each element }//all Shapes implicitly destroyed Now the object is owned by the unique_ptr which will delete the object when it is no longer needed, that is, when its unique_ptr goes out of scope. For the unique_ptr version of user() to work, we need versions of draw_all() and rotate_all() that accept vector<unique_ptr<Shape>>s. Writing many such _all() functions could become tedious, so §3.4 .3 shows an alternative. 3.3 Copy and Move By default, objects can be copied. This is true for objects of user-defined types as well as for built- in types. The default meaning of copy is memberwise copy: copy each member. For example, using complex from §3.2 .1 .1: void test(complex z1) { complex z2 {z1}; // copy initialization complex z3; z3=z2; // copy assignment // ... } Now z1, z2, and z3 have the same value because both the assignment and the initialization copied both members. When we design a class, we must always consider if and how an object might be copied. For simple concrete types, memberwise copy is often exactly the right semantics for copy. For some sophisticated concrete types, such as Vector, memberwise copy is not the right semantics for copy, and for abstract types it almost never is.
ptg10564057 Section 3.3 .1 Copying Containers 73 3.3.1 Copying Containers When a class is a resource handle, that is, it is responsible for an object accessed through a pointer, the default memberwise copy is typically a disaster. Memberwise copy would violate the resource handle’s invariant (§2.4 .3 .2). For example, the default copy would leave a copy of a Vector refer- ring to the same elements as the original: void bad_copy(Vector v1) { Vector v2 = v1; // copy v1’s representation into v2 v1[0] = 2; // v2[0] is now also 2! v2[1] = 3; // v1[1] is now also 3! } Assuming that v1 has four elements, the result can be represented graphically like this: 4 v1: 4 v2: 2 3 Fortunately, the fact that Vector has a destructor is a strong hint that the default (memberwise) copy semantics is wrong and the compiler should at least warn against this example (§17.6). We need to define better copy semantics. Copying of an object of a class is defined by two members: a copy constructor and a copy assignment: class Vector { private: double∗ elem; // elem points to an array of sz doubles int sz; public: Vector(int s); // constructor: establish invariant, acquire resources ̃Vector() { delete[] elem; } // destructor: release resources Vector(const Vector& a); // copy constructor Vector& operator=(const Vector& a); // copy assignment double& operator[](int i); const double& operator[](int i) const; int size() const; }; A suitable definition of a copy constructor for Vector allocates the space for the required number of elements and then copies the elements into it, so that after a copy each Vector has its own copy of the elements:
ptg10564057 74 A Tour of C++: Abstraction Mechanisms Chapter 3 Vector::Vector(const Vector& a) // copy constructor :elem{new double[sz]}, // allocate space for elements sz{a.sz} { for (int i=0; i!=sz; ++i) // copy elements elem[i] = a.elem[i]; } The result of the v2=v1 example can now be presented as: 4 v1: 4 v2: 3 2 Of course, we need a copy assignment in addition to the copy constructor: Vector& Vector::operator=(const Vector& a) // copy assignment { double∗ p = new double[a.sz]; for (int i=0; i!=a.sz; ++i) p[i] = a.elem[i]; delete[] elem; // delete old elements elem = p; sz = a.sz; return ∗this; } The name this is predefined in a member function and points to the object for which the member function is called. A copy constructor and a copy assignment for a class X are typically declared to take an argu- ment of type const X&. 3.3.2 Moving Containers We can control copying by defining a copy constructor and a copy assignment, but copying can be costly for large containers. Consider: Vector operator+(const Vector& a, const Vector& b) { if (a.size()!=b.size()) throw Vector_size_mismatch{}; Vector res(a.size()); for (int i=0; i!=a.size(); ++i) res[i]=a[i]+b[i]; return res; }
ptg10564057 Section 3.3 .2 Moving Containers 75 Returning from a + involves copying the result out of the local variable res and into some place where the caller can access it. We might use this + like this: void f(const Vector& x, const Vector& y, const Vector& z) { Vector r; // ... r = x+y+z; // ... } That would be copying a Vector at least twice (one for each use of the + operator). If a Vector is large, say, 10,000 doubles, that could be embarrassing. The most embarrassing part is that res in operator+() is never used again after the copy. We didn’t really want a copy; we just wanted to get the result out of a function: we wanted to move a Vector rather than to copy it. Fortunately, we can state that intent: class Vector { // ... Vector(const Vector& a); // copy constructor Vector& operator=(const Vector& a); // copy assignment Vector(Vector&& a); // move constructor Vector& operator=(Vector&& a); // move assignment }; Given that definition, the compiler will choose the move constructor to implement the transfer of the return value out of the function. This means that r=x+y+z will involve no copying of Vectors. Instead, Vectors are just moved. As is typical, Vector’s move constructor is trivial to define: Vector::Vector(Vector&& a) :elem{a.elem}, // "grab the elements" from a sz{a.sz} { a.elem = nullptr; // now a has no elements a.sz = 0; } The && means ‘‘rvalue reference’’ and is a reference to which we can bind an rvalue (§6.4 .1). The word ‘‘rvalue’’ is intended to complement ‘‘lvalue,’’ which roughly means ‘‘something that can appear on the left-hand side of an assignment.’’ So an rvalue is – to a first approximation – a value that you can’t assign to, such as an integer returned by a function call, and an rvalue reference is a reference to something that nobody else can assign to. The res local variable in operator+() for Vec- tors is an example. A move constructor does not take a const argument: after all, a move constructor is supposed to remove the value from its argument. A move assignment is defined similarly. A move operation is applied when an rvalue reference is used as an initializer or as the right- hand side of an assignment.
ptg10564057 76 A Tour of C++: Abstraction Mechanisms Chapter 3 After a move, a moved-from object should be in a state that allows a destructor to be run. Typi- cally, we should also allow assignment to a moved-from object (§17.5, §17.6 .2). Where the programmer knows that a value will not be used again, but the compiler can’t be expected to be smart enough to figure that out, the programmer can be specific: Vector f() { Vector x(1000); Vector y(1000); Vector z(1000); // ... z=x; //we get a copy y = std::move(x); // we get a move // ... return z; //wegetamove }; The standard-library function move() returns an rvalue reference to its argument. Just before the return we have: nullptr 0 x: 1000 y: 1000 z: 1 2 ... 1 2 ... When z is destroyed, it too has been moved from (by the return) so that, like x, it is empty (it holds no elements). 3.3.3 Resource Management By defining constructors, copy operations, move operations, and a destructor, a programmer can provide complete control of the lifetime of a contained resource (such as the elements of a con- tainer). Furthermore, a move constructor allows an object to move simply and cheaply from one scope to another. That way, objects that we cannot or would not want to copy out of a scope can be simply and cheaply moved out instead. Consider a standard-library thread representing a concur- rent activity (§5.3 .1) and a Vector of a million doubles. We can’t copy the former and don’t want to copy the latter. std::vector<thread> my_threads; Vector init(int n) { thread t {heartbeat}; // run heartbeat concurrently (on its own thread) my_threads.push_back(move(t)); // move t into my_threads // ... more initialization ...
ptg10564057 Section 3.3 .3 Resource Management 77 Vector vec(n); for (int i=0; i<vec.size(); ++i) vec[i] = 777; return vec; // move res out of init() } auto v = init(); // start heartbeat and initialize v This makes resource handles, such as Vector and thread, an alternative to using pointers in many cases. In fact, the standard-library ‘‘smart pointers,’’ such as unique_ptr, are themselves resource handles (§5.2 .1). I used the standard-library vector to hold the threads because we don’t get to parameterize Vector with an element type until §3.4 .1 . In very much the same way as new and delete disappear from application code, we can make pointers disappear into resource handles. In both cases, the result is simpler and more maintainable code, without added overhead. In particular, we can achieve strong resource safety; that is, we can eliminate resource leaks for a general notion of a resource. Examples are vectors holding memory, threads holding system threads, and fstreams holding file handles. 3.3.4 Suppressing Operations Using the default copy or move for a class in a hierarchy is typically a disaster: given only a pointer to a base, we simply don’t know what members the derived class has (§3.2 .2), so we can’t know how to copy them. So, the best thing to do is usually to delete the default copy and move opera- tions, that is, to eliminate the default definitions of those two operations: class Shape { public: Shape(const Shape&) =delete; // no copy operations Shape& operator=(const Shape&) =delete; Shape(Shape&&) =delete; // no move operations Shape& operator=(Shape&&) =delete; ̃Shape(); // ... }; Now an attempt to copy a Shape will be caught by the compiler. If you need to copy an object in a class hierarchy, write some kind of clone function (§22.2 .4). In this particular case, if you forgot to delete a copy or move operation, no harm is done. A move operation is not implicitly generated for a class where the user has explicitly declared a de- structor. Furthermore, the generation of copy operations is deprecated in this case (§44.2 .3). This can be a good reason to explicitly define a destructor even where the compiler would have implic- itly provided one (§17.2 .3). A base class in a class hierarchy is just one example of an object we wouldn’t want to copy. A resource handle generally cannot be copied just by copying its members (§5.2, §17.2.2). The =delete mechanism is general, that is, it can be used to suppress any operation (§17.6 .4).
ptg10564057 78 A Tour of C++: Abstraction Mechanisms Chapter 3 3.4 Templates Someone who wants a vector is unlikely always to want a vector of doubles. A vector is a general concept, independent of the notion of a floating-point number. Consequently, the element type of a vector ought to be represented independently. A template is a class or a function that we parame- terize with a set of types or values. We use templates to represent concepts that are best understood as something very general from which we can generate specific types and functions by specifying arguments, such as the element type double. 3.4.1 Parameterized Types We can generalize our vector-of-doubles type to a vector-of-anything type by making it a template and replacing the specific type double with a parameter. For example: template<typename T> class Vector { private: T∗ elem; // elem points to an array of sz elements of type T int sz; public: Vector(int s); // constructor: establish invariant, acquire resources ̃Vector() { delete[] elem; } // destructor: release resources // ... copy and move operations ... T& operator[](int i); const T& operator[](int i) const; int size() const { return sz; } }; The template<typename T> prefix makes T a parameter of the declaration it prefixes. It is C++’s ver- sion of the mathematical ‘‘for all T’’ or more precisely ‘‘for all types T.’’ The member functions might be defined similarly: template<typename T> Vector<T>::Vector(int s) { if (s<0) throw Negative_size{}; elem = new T[s]; sz=s; } template<typename T> const T& Vector<T>::operator[](int i) const { if (i<0 || size()<=i) throw out_of_range{"Vector::operator[]"}; return elem[i]; }
ptg10564057 Section 3.4 .1 Parameterized Types 79 Given these definitions, we can define Vectors like this: Vector<char> vc(200); // vector of 200 characters Vector<string> vs(17); // vector of 17 strings Vector<list<int>> vli(45); // vector of 45 lists of integers The >> in Vector<list<int>> terminates the nested template arguments; it is not a misplaced input operator. It is not (as in C++98) necessary to place a space between the two >s. We can use Vectors like this: void write(const Vector<string>& vs) // Vector of some strings { for (int i = 0; i!=vs.size(); ++i) cout << vs[i] << '\n'; } To support the range-for loop for our Vector, we must define suitable begin() and end() functions: template<typename T> T∗ begin(Vector<T>& x) { return &x[0]; // pointer to first element } template<typename T> T∗ end(Vector<T>& x) { return x.begin()+x.size(); // pointer to one-past-last element } Given those, we can write: void f2(const Vector<string>& vs) // Vector of some strings { for (auto& s : vs) cout << s << '\n'; } Similarly, we can define lists, vectors, maps (that is, associative arrays), etc., as templates (§4.4, §23.2, Chapter 31). Templates are a compile-time mechanism, so their use incurs no run-time overhead compared to ‘‘handwritten code’’ (§23.2 .2). 3.4.2 Function Templates Templates have many more uses than simply parameterizing a container with an element type. In particular, they are extensively used for parameterization of both types and algorithms in the stan- dard library (§4.4.5, §4.5 .5). For example, we can write a function that calculates the sum of the element values of any container like this:
ptg10564057 80 A Tour of C++: Abstraction Mechanisms Chapter 3 template<typename Container, typename Value> Value sum(const Container& c, Value v) { for(autox:c) v+=x; return v; } The Value template argument and the function argument v are there to allow the caller to specify the type and initial value of the accumulator (the variable in which to accumulate the sum): void user(Vector<int>& vi, std::list<double>& ld, std::vector<complex<double>>& vc) { int x = sum(vi,0); // the sum of a vector of ints (add ints) double d = sum(vi,0.0); // the sum of a vector of ints (add doubles) double dd = sum(ld,0.0); // the sum of a list of doubles auto z = sum(vc,complex<double>{}); // the sum of a vector of complex<double> // the initial value is {0.0,0.0} } The point of adding intsinadouble would be to gracefully handle a number larger than the largest int. Note how the types of the template arguments for sum<T,V> are deduced from the function arguments. Fortunately, we do not need to explicitly specify those types. This sum() is a simplified version of the standard-library accumulate() (§40.6). 3.4.3 Function Objects One particularly useful kind of template is the function object (sometimes called a functor), which is used to define objects that can be called like functions. For example: template<typename T> class Less_than { const T val; // value to compare against public: Less_than(const T& v) :val(v) { } bool operator()(const T& x) const { return x<val; } // call operator }; The function called operator() implements the ‘‘function call,’’ ‘‘call,’’ or ‘‘application’’ operator (). We can define named variables of type Less_than for some argument type: Less_than<int> lti {42}; // lti(i) will compare i to 42 using < (i<42) Less_than<string> lts {"Backus"}; // lts(s) will compare s to "Backus" using < (s<"Backus") We can call such an object, just as we call a function: void fct(int n, const string & s) { bool b1 = lti(n); // true if n<42 bool b2 = lts(s); // true if s<"Backus" // ... }
ptg10564057 Section 3.4 .3 Function Objects 81 Such function objects are widely used as arguments to algorithms. For example, we can count the occurrences of values for which a predicate returns true: template<typename C, typename P> int count(const C& c, P pred) { intcnt=0; for (const auto& x : c) if (pred(x)) ++cnt; return cnt; } A predicate is something that we can invoke to return true or false. For example: void f(const Vector<int>& vec, const list<string>& lst, int x, const string& s) { cout << "number of values less than " << x << ": " << count(vec,Less_than<int>{x}) << '\n'; cout << "number of values less than " << s << ": " << count(lst,Less_than<string>{s}) << '\n'; } Here, Less_than<int>{x} constructs an object for which the call operator compares to the int called x; Less_than<string>{s} constructs an object that compares to the string called s. The beauty of these function objects is that they carry the value to be compared against with them. We don’t have to write a separate function for each value (and each type), and we don’t have to introduce nasty global variables to hold values. Also, for a simple function object like Less_than inlining is simple, so that a call of Less_than is far more efficient than an indirect function call. The ability to carry data plus their efficiency make function objects particularly useful as arguments to algorithms. Function objects used to specify the meaning of key operations of a general algorithm (such as Less_than for count()) are often referred to as policy objects. We have to define Less_than separately from its use. That could be seen as inconvenient. Con- sequently, there is a notation for implicitly generating function objects: void f(const Vector<int>& vec, const list<string>& lst, int x, const string& s) { cout << "number of values less than " << x << ": " << count(vec,[&](int a){ return a<x; }) << '\n'; cout << "number of values less than " << s << ": " << count(lst,[&](const string& a){ return a<s; }) << '\n'; } The notation [&](int a){ return a<x; } is called a lambda expression (§11.4). It generates a function object exactly like Less_than<int>{x}. The [&] is a capture list specifying that local names used (such as x) will be passed by reference. Had we wanted to ‘‘capture’’ only x, we could have said
ptg10564057 82 A Tour of C++: Abstraction Mechanisms Chapter 3 so: [&x]. Had we wanted to give the generated object a copy of x, we could have said so: [=x]. Cap- ture nothing is [], capture all local names used by reference is [&], and capture all local names used by value is [=]. Using lambdas can be convenient and terse, but also obscure. For nontrivial actions (say, more than a simple expression), I prefer to name the operation so as to more clearly state its purpose and to make it available for use in several places in a program. In §3.2 .4, we noticed the annoyance of having to write many functions to perform operations on elements of vectors of pointers and unique_ptrs, such as draw_all() and rotate_all(). Function objects (in particular, lambdas) can help by allowing us to separate the traversal of the container from the specification of what is to be done with each element. First, we need a function that applies an operation to each object pointed to by the elements of a container of pointers: template<class C, class Oper> void for_all(C& c, Oper op) // assume that C is a container of pointers { for (auto& x : c) op(∗x); // pass op() a reference to each element pointed to } Now, we can write a version of user() from §3.2 .4 without writing a set of _all functions: void user() { vector<unique_ptr<Shape>> v; while (cin) v.push_back(read_shape(cin)); for_all(v,[](Shape& s){ s.draw(); }); // draw_all() for_all(v,[](Shape& s){ s.rotate(45); }); // rotate_all(45) } I pass a reference to Shape to a lambda so that the lambda doesn’t have to care exactly how the objects are stored in the container. In particular, those for_all() calls would still work if I changed v to a vector<Shape∗>. 3.4.4 Variadic Templates A template can be defined to accept an arbitrary number of arguments of arbitrary types. Such a template is called a variadic template. For example: template<typename T, typename... Tail> void f(T head, Tail... tail) { g(head); // do something to head f(tail...); // try again with tail } voidf(){} // do nothing The key to implementing a variadic template is to note that when you pass a list of arguments to it,
ptg10564057 Section 3.4 .4 Variadic Templates 83 you can separate the first argument from the rest. Here, we do something to the first argument (the head) and then recursively call f() with the rest of the arguments (the tail). The ellipsis, ..., is used to indicate ‘‘the rest’’ of a list. Eventually, of course, tail will become empty and we need a separate function to deal with that. We can call this f() like this: int main() { cout << "first: "; f(1,2.2,"hello"); cout << "\nsecond: " f(0.2,'c',"yuck!",0,1,2); cout << "\n"; } This would call f(1,2.2,"hello"), which will call f(2.2,"hello"), which will call f("hello"), which will call f(). What might the call g(head) do? Obviously, in a real program it will do whatever we wanted done to each argument. For example, we could make it write its argument (here, head) to output: template<typename T> void g(T x) { cout<<x<<""; } Given that, the output will be: first: 1 2.2 hello second: 0.2 c yuck! 0 1 2 It seems that f() is a simple variant of printf() printing arbitrary lists or values – implemented in three lines of code plus their surrounding declarations. The strength of variadic templates (sometimes just called variadics) is that they can accept any arguments you care to give them. The weakness is that the type checking of the interface is a possi- bly elaborate template program. For details, see §28.6 . For examples, see §34.2 .4 .2 (N-tuples) and Chapter 29 (N-dimensional matrices). 3.4.5 Aliases Surprisingly often, it is useful to introduce a synonym for a type or a template (§6.5). For example, the standard header <cstddef> contains a definition of the alias size_t, maybe: using size_t = unsigned int; The actual type named size_t is implementation-dependent, so in another implementation size_t may be an unsigned long. Having the alias size_t allows the programmer to write portable code. It is very common for a parameterized type to provide an alias for types related to their template arguments. For example:
ptg10564057 84 A Tour of C++: Abstraction Mechanisms Chapter 3 template<typename T> class Vector { public: using value_type = T; // ... }; In fact, every standard-library container provides value_type as the name of its value type (§31.3 .1). This allows us to write code that will work for every container that follows this convention. For example: template<typename C> using Element_type = typename C::value_type; template<typename Container> void algo(Container& c) { Vector<Element_type<Container>> vec; // keep results here // ... } The aliasing mechanism can be used to define a new template by binding some or all template argu- ments. For example: template<typename Key, typename Value> class Map { // ... }; template<typename Value> using String_map = Map<string,Value>; String_map<int> m; // m is a Map<string,int> See §23.6 . 3.5 Advice [1] Express ideas directly in code; §3.2. [2] Define classes to represent application concepts directly in code; §3.2. [3] Use concrete classes to represent simple concepts and performance-critical components; §3.2 .1 . [4] Avoid ‘‘naked’’ new and delete operations; §3.2 .1 .2 . [5] Use resource handles and RAII to manage resources; §3.2 .1.2 . [6] Use abstract classes as interfaces when complete separation of interface and implementation is needed; §3.2 .2. [7] Use class hierarchies to represent concepts with inherent hierarchical structure; §3.2 .4.
ptg10564057 Section 3.5 Advice 85 [8] When designing a class hierarchy, distinguish between implementation inheritance and inter- face inheritance; §3.2.4 . [9] Control construction, copy, move, and destruction of objects; §3.3 . [10] Return containers by value (relying on move for efficiency); §3.3 .2 . [11] Provide strong resource safety; that is, never leak anything that you think of as a resource; §3.3 .3 . [12] Use containers, defined as resource handle templates, to hold collections of values of the same type; §3.4 .1 . [13] Use function templates to represent general algorithms; §3.4 .2 . [14] Use function objects, including lambdas, to represent policies and actions; §3.4.3 . [15] Use type and template aliases to provide a uniform notation for types that may vary among similar types or among implementations; §3.4 .5.
ptg10564057 This page intentionally left blank
ptg10564057 4 A Tour of C++: Containers and Algorithms Why waste time learning when ignorance is instantaneous? – Hobbes • Libraries Standard-Library Overview; The Standard-Library Headers and Namespace • Strings • Stream I/O Output; Input; I/O of User-Defined Types • Containers vector; list; map; unordered_map; Container Overview • Algorithms Use of Iterators; Iterator Types; Stream Iterators; Predicates; Algorithm Overview; Con- tainer Algorithms • Advice 4.1 Libraries No significant program is written in just a bare programming language. First, a set of libraries is developed. These then form the basis for further work. Most programs are tedious to write in the bare language, whereas just about any task can be rendered simple by the use of good libraries. Continuing from Chapters 2 and 3, this chapter and the next give a quick tour of key standard- library facilities. I assume that you have programmed before. If not, please consider reading a textbook, such as Programming: Principles and Practice Using C++ [Stroustrup,2009], before continuing. Even if you have programmed before, the libraries you used or the applications you wrote may be very different from the style of C++ presented here. If you find this ‘‘lightning tour’’ confusing, you might skip to the more systematic and bottom-up language presentation starting in Chapter 6. Similarly, a more systematic description of the standard library starts in Chapter 30.
ptg10564057 88 A Tour of C++: Containers and Algorithms Chapter 4 I very briefly present useful standard-library types, such as string, ostream, vector, map (this chapter), unique_ptr, thread, regex, and complex (Chapter 5), as well as the most common ways of using them. Doing this allows me to give better examples in the following chapters. As in Chapter 2 and Chapter 3, you are strongly encouraged not to be distracted or discouraged by an incomplete understanding of details. The purpose of this chapter is to give you a taste of what is to come and to convey a basic understanding of the most useful library facilities. The specification of the standard library is almost two thirds of the ISO C++ standard. Explore it, and prefer it to home-made alternatives. Much though have gone into its design, more still into its implementations, and much effort will go into its maintenance and extension. The standard-library facilities described in this book are part of every complete C++ implemen- tation. In addition to the standard-library components, most implementations offer ‘‘graphical user interface’’ systems (GUIs), Web interfaces, database interfaces, etc. Similarly, most application development environments provide ‘‘foundation libraries’’ for corporate or industrial ‘‘standard’’ development and/or execution environments. Here, I do not describe such systems and libraries. The intent is to provide a self-contained description of C++ as defined by the standard and to keep the examples portable, except where specifically noted. Naturally, a programmer is encouraged to explore the more extensive facilities available on most systems. 4.1.1 Standard-Library Overview The facilities provided by the standard library can be classified like this: • Run-time language support (e.g ., for allocation and run-time type information); see §30.3 . • The C standard library (with very minor modifications to minimize violations of the type system); see Chapter 43. • Strings and I/O streams (with support for international character sets and localization); see Chapter 36, Chapter 38, and Chapter 39. I/O streams is an extensible framework to which users can add their own streams, buffering strategies, and character sets. • A framework of containers (such as vector and map) and algorithms (such as find(), sort(), and merge()); see §4.4, §4.5, Chapters 31-33 . This framework, conventionally called the STL [Stepanov,1994], is extensible so users can add their own containers and algorithms. • Support for numerical computation (such as standard mathematical functions, complex numbers, vectors with arithmetic operations, and random number generators); see §3.2 .1 .1 and Chapter 40. • Support for regular expression matching; see §5.5 and Chapter 37. • Support for concurrent programming, including threads and locks; see §5.3 and Chapter 41. The concurrency support is foundational so that users can add support for new models of concurrency as libraries. • Utilities to support template metaprogramming (e.g ., type traits; §5.4 .2, §28.2 .4, §35.4), STL-style generic programming (e.g ., pair; §5.4 .3, §34.2 .4 .1), and general programming (e.g., clock; §5.4 .1, §35.2). • ‘‘Smart pointers’’ for resource management (e.g ., unique_ptr and shared_ptr; §5.2 .1, §34.3) and an interface to garbage collectors (§34.5). • Special-purpose containers, such as array (§34.2 .1), bitset (§34.2.2), and tuple (§34.2 .4 .2).
ptg10564057 Section 4.1 .1 Standard-Library Overview 89 The main criteria for including a class in the library were that: • it could be helpful to almost every C++ programmer (both novices and experts), • it could be provided in a general form that did not add significant overhead compared to a simpler version of the same facility, and • that simple uses should be easy to learn (relative to the inherent complexity of their task). Essentially, the C++ standard library provides the most common fundamental data structures together with the fundamental algorithms used on them. 4.1.2 The Standard-library Headers and Namespace Every standard-library facility is provided through some standard header. For example: #include<string> #include<list> This makes the standard string and list available. The standard library is defined in a namespace (§2.4 .2, §14.3 .1) called std. To use standard library facilities, the std:: prefix can be used: std::string s {"Four legs Good; two legs Baaad!"}; std::list<std::string> slogans {"War is peace", "Freedom is Slavery", "Ignorance is Strength"}; For simplicity, I will rarely use the std:: prefix explicitly in examples. Neither will I always #include the necessary headers explicitly. To compile and run the program fragments here, you must #include the appropriate headers (as listed in §4.4 .5, §4.5 .5, and §30.2) and make the names they declare accessible. For example: #include<string> // make the standard string facilities accessible using namespace std; // make std names available without std:: prefix string s {"C++ is a general−purpose programming language"}; // OK: string is std::string It is generally in poor taste to dump every name from a namespace into the global namespace. However, in this book, I use the standard library almost exclusively and it is good to know what it offers. So, I don’t prefix every use of a standard library name with std::. Nor do I #include the appropriate headers in every example. Assume that done. Here is a selection of standard-library headers, all supplying declarations in namespace std: Selected Standard Library Headers (continues) <algorithm> copy(), find(), sort() §32.2 §iso.25 <array> array §34.2 .1 §iso.23.3 .2 <chrono> duration, time_point §35.2 §iso.20.11.2 <cmath> sqrt(), pow() §40.3 §iso.26.8 <complex> complex, sqrt(), pow() §40.4 §iso.26.8 <fstream> fstream, ifstream, ofstream §38.2 .1 §iso.27.9 .1 <future> future, promise §5.3 .5 §iso.30 .6 <iostream> istream, ostream, cin, cout §38.1 §iso.27.4
ptg10564057 90 A Tour of C++: Containers and Algorithms Chapter 4 Selected Standard Library Headers (continued) <map> map, multimap §31.4 .3 §iso.23.4 .4 <memory> unique_ptr, shared_ptr, allocator §5.2 .1 §iso.20.6 <random> default_random_engine, normal_distribution §40.7 §iso.26.5 <regex> regex, smatch Chapter 37 §iso.28.8 <string> string, basic_string Chapter 36 §iso.21 .3 <set> set, multiset §31.4 .3 §iso.23.4 .6 <sstream> istrstream, ostrstream §38.2 .2 §iso.27.8 <thread> thread §5.3 .1 §iso.30 .3 <unordered_map> unordered_map, unordered_multimap §31.4 .3 .2 §iso.23.5 .4 <utility> move(), swap(), pair §35.5 §iso.20.1 <vector> vector §31.4 §iso.23.3 .6 This listing is far from complete; see §30.2 for more information. 4.2 Strings The standard library provides a string type to complement the string literals. The string type pro- vides a variety of useful string operations, such as concatenation. For example: string compose(const string& name, const string& domain) { return name + '@' + domain; } auto addr = compose("dmr","bell−labs.com"); Here, addr is initialized to the character sequence dmr@bell−labs.com. ‘‘Addition’’ of strings means concatenation. You can concatenate a string, a string literal, a C-style string, or a character to a string. The standard string has a move constructor so returning even long strings by value is effi- cient (§3.3 .2). In many applications, the most common form of concatenation is adding something to the end of a string. This is directly supported by the += operation. For example: void m2(string& s1, string& s2) { s1 = s1 + '\n'; // append newline s2 += '\n'; // append newline } The two ways of adding to the end of a string are semantically equivalent, but I prefer the latter because it is more explicit about what it does, more concise, and possibly more efficient. A string is mutable. In addition to = and +=, subscripting (using []) and substring operations are supported. The standard-library string is described in Chapter 36. Among other useful features, it provides the ability to manipulate substrings. For example:
ptg10564057 Section 4.2 Strings 91 string name = "Niels Stroustrup"; void m3() { string s = name.substr(6,10); // s = "Stroustrup" name.replace(0,5,"nicholas"); // name becomes "nicholas Stroustrup" name[0] = toupper(name[0]); // name becomes "Nicholas Stroustrup" } The substr() operation returns a string that is a copy of the substring indicated by its arguments. The first argument is an index into the string (a position), and the second is the length of the desired substring. Since indexing starts from 0, s gets the value Stroustrup. The replace() operation replaces a substring with a value. In this case, the substring starting at 0 with length 5 is Niels; it is replaced by nicholas. Finally, I replace the initial character with its uppercase equivalent. Thus, the final value of name is Nicholas Stroustrup. Note that the replace- ment string need not be the same size as the substring that it is replacing. Naturally, strings can be compared against each other and against string literals. For example: string incantation; void respond(const string& answer) { if (answer == incantation) { // perform magic } else if (answer == "yes") { // ... } // ... } The string library is described in Chapter 36. The most common techniques for implementing string are presented in the String example (§19.3). 4.3 Stream I/O The standard library provides formatted character input and output through the iostream library. The input operations are typed and extensible to handle user-defined types. This section is a very brief introduction to the use of iostreams; Chapter 38 is a reasonably complete description of the iostream library facilities. Other forms of user interaction, such as graphical I/O, are handled through libraries that are not part of the ISO standard and therefore not described here. 4.3.1 Output The I/O stream library defines output for every built-in type. Further, it is easy to define output of a user-defined type (§4.3 .3). The operator << (‘‘put to’’) is used as an output operator on objects of
ptg10564057 92 A Tour of C++: Containers and Algorithms Chapter 4 type ostream; cout is the standard output stream and cerr is the standard stream for reporting errors. By default, values written to cout are converted to a sequence of characters. For example, to output the decimal number 10, we can write: void f() { cout << 10; } This places the character 1 followed by the character 0 on the standard output stream. Equivalently, we could write: void g() { int i {10}; cout << i; } Output of different types can be combined in the obvious way: void h(int i) { cout << "the value of i is "; cout << i; cout << '\n'; } For h(10), the output will be: thevalueofiis10 People soon tire of repeating the name of the output stream when outputting several related items. Fortunately, the result of an output expression can itself be used for further output. For example: void h2(int i) { cout<<"thevalueofiis"<<i<<'\n'; } This h2() produces the same output as h(). A character constant is a character enclosed in single quotes. Note that a character is output as a character rather than as a numerical value. For example: void k() { intb='b'; // note: char implicitly converted to int char c = 'c'; cout<<'a'<<b<<c; } The integer value of the character 'b' is 98 (in the ASCII encoding used on the C++ implementation that I used), so this will output a98c.
ptg10564057 Section 4.3 .2 Input 93 4.3.2 Input The standard library offers istreams for input. Like ostreams, istreams deal with character string representations of built-in types and can easily be extended to cope with user-defined types. The operator >> (‘‘get from’’) is used as an input operator; cin is the standard input stream. The type of the right-hand operand of >> determines what input is accepted and what is the target of the input operation. For example: void f() { int i; cin >> i; // read an integer into i double d; cin >> d; // read a double-precision floating-point number into d } This reads a number, such as 1234, from the standard input into the integer variable i and a floating- point number, such as 12.34e5, into the double-precision floating-point variable d. Often, we want to read a sequence of characters. A convenient way of doing that is to read into a string. For example: void hello() { cout << "Please enter your name\n"; string str; cin >> str; cout << "Hello, " << str << "!\n"; } If you type in Eric the response is: Hello, Eric! By default, a whitespace character (§7.3 .2), such as a space, terminates the read, so if you enter Eric Bloodaxe pretending to be the ill-fated king of York, the response is still: Hello, Eric! You can read a whole line (including the terminating newline character) using the getline() function. For example: void hello_line() { cout << "Please enter your name\n"; string str; getline(cin,str); cout << "Hello, " << str << "!\n"; } With this program, the input Eric Bloodaxe yields the desired output: Hello, Eric Bloodaxe!
ptg10564057 94 A Tour of C++: Containers and Algorithms Chapter 4 The newline that terminated the line is discarded, so cin is ready for the next input line. The standard strings have the nice property of expanding to hold what you put in them; you don’t have to precalculate a maximum size. So, if you enter a couple of megabytes of semicolons, the program will echo pages of semicolons back at you. 4.3.3 I/O of User-Defined Types In addition to the I/O of built-in types and standard strings, the iostream library allows programmers to define I/O for their own types. For example, consider a simple type Entry that we might use to represent entries in a telephone book: struct Entry { string name; int number; }; We can define a simple output operator to write an Entry using a {"name",number} format similar to the one we use for initialization in code: ostream& operator<<(ostream& os, const Entry& e) { return os << "{\"" << e.name << "\", " << e.number << "}"; } A user-defined output operator takes its output stream (by reference) as its first argument and returns it as its result. See §38.4 .2 for details. The corresponding input operator is more complicated because it has to check for correct for- matting and deal with errors: istream& operator>>(istream& is, Entry& e) // read { "name" , number } pair. Note: formatted with { " " , and } { char c, c2; if (is>>c && c=='{' && is>>c2 && c2=='"') { // start with a { " string name; // the default value of a string is the empty string: "" while (is.get(c) && c!='"') // anything before a " is part of the name name+=c; if (is>>c && c==',') { int number = 0; if (is>>number>>c && c=='}') { // read the number and a } e = {name,number}; // assign to the entry return is; } } } is.setf(ios_base::failbit); // register the failure in the stream return is; } An input operation returns a reference to its istream which can be used to test if the operation
ptg10564057 Section 4.3 .3 I/O of User-Defined Types 95 succeeded. For example, when used as a condition, is>>c means ‘‘Did we succeed at reading from is into c?’’ The is>>c skips whitespace by default, but is.get(c) does not, so that this Entry-input operator ignores (skips) whitespace outside the name string, but not within it. For example: { "John Marwood Cleese" , 123456 } {"Michael Edward Palin",987654} We can read such a pair of values from input into an Entry like this: for (Entry ee; cin>>ee; ) // read from cin into ee cout << ee << '\n'; // write ee to cout The output is: {"John Marwood Cleese", 123456} {"Michael Edward Palin", 987654} See §38.4 .1 for more technical details and techniques for writing input operators for user-defined types. See §5.5 and Chapter 37 for a more systematic technique for recognizing patterns in streams of characters (regular expression matching). 4.4 Containers Most computing involves creating collections of values and then manipulating such collections. Reading characters into a string and printing out the string is a simple example. A class with the main purpose of holding objects is commonly called a container. Providing suitable containers for a given task and supporting them with useful fundamental operations are important steps in the construction of any program. To illustrate the standard-library containers, consider a simple program for keeping names and telephone numbers. This is the kind of program for which different approaches appear ‘‘simple and obvious’’ to people of different backgrounds. The Entry class from §4.3 .3 can be used to hold a simple phone book entry. Here, we deliberately ignore many real-world complexities, such as the fact that many phone numbers do not have a simple representation as a 32-bit int. 4.4.1 vector The most useful standard-library container is vector.Avector is a sequence of elements of a given type. The elements are stored contiguously in memory: 6 vector: elem: sz: 0: 1: 2: 3: 4: 5: The Vector examples in §3.2 .2 and §3.4 give an idea of the implementation of vector and §13.6 and §31.4 provide an exhaustive discussion.
ptg10564057 96 A Tour of C++: Containers and Algorithms Chapter 4 We can initialize a vector with a set of values of its element type: vector<Entry> phone_book = { {"David Hume",123456}, {"Karl Popper",234567}, {"Bertrand Arthur William Russell",345678} }; Elements can be accessed through subscripting: void print_book(const vector<Entry>& book) { for (int i = 0; i!=book.size(); ++i) cout << book[i] << '\n'; } As usual, indexing starts at 0 so that book[0] holds the entry for David Hume. The vector member function size() gives the number of elements. The elements of a vector constitute a range, so we can use a range-for loop (§2.2 .5): void print_book(const vector<Entry>& book) { for (const auto& x : book) // for "auto" see §2.2.2 cout << x << '\n'; } When we define a vector, we give it an initial size (initial number of elements): vector<int> v1 = {1, 2, 3, 4}; // sizeis4 vector<string> v2; // sizeis0 vector<Shape∗> v3(23); // size is 23; initial element value: nullptr vector<double> v4(32,9.9); // size is 32; initial element value: 9.9 An explicit size is enclosed in ordinary parentheses, for example, (23), and by default the elements are initialized to the element type’s default value (e.g., nullptr for pointers and 0 for numbers). If you don’t want the default value, you can specify one as a second argument (e.g ., 9.9 for the 32 ele- ments of v4). The initial size can be changed. One of the most useful operations on a vector is push_back(), which adds a new element at the end of a vector, increasing its size by one. For example: void input() { for (Entry e; cin>>e;) phone_book.push_back(e); } This reads Entrys from the standard input into phone_book until either the end-of-input (e.g ., the end of a file) is reached or the input operation encounters a format error. The standard-library vector is implemented so that growing a vector by repeated push_back()s is efficient. A vector can be copied in assignments and initializations. For example: vector<Entry> book2 = phone_book;
ptg10564057 Section 4.4 .1 vector 97 Copying and moving of vectors are implemented by constructors and assignment operators as described in §3.3. Assigning a vector involves copying its elements. Thus, after the initialization of book2, book2 and phone_book hold separate copies of every Entry in the phone book. When a vector holds many elements, such innocent-looking assignments and initializations can be expen- sive. Where copying is undesirable, references or pointers (§7.2, §7.7) or move operations (§3.3 .2, §17.5 .2) should be used. 4.4 .1.1 Elements Like all standard-library containers, vector is a container of elements of some type T, that is, a vector<T>. Just about any type qualifies as an element type: built-in numeric types (such as char, int, and double), user-defined types (such as string, Entry, list<int>, and Matrix<double,2>), and point- ers (such as const char∗, Shape∗, and double∗). When you insert a new element, its value is copied into the container. For example, when you put an integer with the value 7 into a container, the resulting element really has the value 7. The element is not a reference or a pointer to some object containing 7. This makes for nice compact containers with fast access. For people who care about memory sizes and run-time performance this is critical. 4.4 .1.2 Range Checking The standard-library vector does not guarantee range checking (§31.2 .2). For example: void silly(vector<Entry>& book) { int i = book[ph.size()].number; // book.size() is out of range // ... } That initialization is likely to place some random value in i rather than giving an error. This is undesirable, and out-of-range errors are a common problem. Consequently, I often use a simple range-checking adaptation of vector: template<typename T> class Vec : public std::vector<T> { public: using vector<T>::vector; // use the constructors from vector (under the name Vec); see §20.3.5.1 T& operator[](int i) // range check { return vector<T>::at(i); } const T& operator[](int i) const // range check const objects; §3.2.1.1 { return vector<T>::at(i); } }; Ve c inherits everything from vector except for the subscript operations that it redefines to do range checking. The at() operation is a vector subscript operation that throws an exception of type out_of_range if its argument is out of the vector’s range (§2.4 .3 .1, §31.2 .2).
ptg10564057 98 A Tour of C++: Containers and Algorithms Chapter 4 For Ve c, an out-of-range access will throw an exception that the user can catch. For example: void checked(Vec<Entry>& book) { try { book[book.size()] = {"Joe",999999}; // will throw an exception // ... } catch (out_of_range) { cout << "range error\n"; } } The exception will be thrown, and then caught (§2.4 .3 .1, Chapter 13). If the user doesn’t catch an exception, the program will terminate in a well-defined manner rather than proceeding or failing in an undefined manner. One way to minimize surprises from uncaught exceptions is to use a main() with a try-block as its body. For example: int main() try { // your code } catch (out_of_range) { cerr << "range error\n"; } catch (...) { cerr << "unknown exception thrown\n"; } This provides default exception handlers so that if we fail to catch some exception, an error mes- sage is printed on the standard error-diagnostic output stream cerr (§38.1). Some implementations save you the bother of defining Vec (or equivalent) by providing a range- checked version of vector (e.g ., as a compiler option). 4.4.2 list The standard library offers a doubly-linked list called list: 4 list: links links links links We use a list for sequences where we want to insert and delete elements without moving other ele- ments. Insertion and deletion of phone book entries could be common, so a list could be appropri- ate for representing a simple phone book. For example: list<Entry> phone_book = { {"David Hume",123456},
ptg10564057 Section 4.4 .2 list 99 {"Karl Popper",234567}, {"Bertrand Arthur William Russell",345678} }; When we use a linked list, we tend not to access elements using subscripting the way we com- monly do for vectors. Instead, we might search the list looking for an element with a given value. To do this, we take advantage of the fact that a list is a sequence as described in §4.5: int get_number(const string& s) { for (const auto& x : phone_book) if (x.name==s) return x.number; return 0; // use 0 to represent "number not found" } The search for s starts at the beginning of the list and proceeds until s is found or the end of phone_book is reached. Sometimes, we need to identify an element in a list. For example, we may want to delete it or insert a new entry before it. To do that we use an iterator:alist iterator identifies an element of a list and can be used to iterate through a list (hence its name). Every standard-library container pro- vides the functions begin() and end(), which return an iterator to the first and to one-past-the-last element, respectively (§4.5, §33.1 .1). Using iterators explicitly, we can – less elegantly – write the get_number() function like this: int get_number(const string& s) { for (auto p = phone_book.begin(); p!=phone_book.end(); ++p) if (p−>name==s) return p−>number; return 0; // use 0 to represent "number not found" } In fact, this is roughly the way the terser and less error-prone range-for loop is implemented by the compiler. Given an iterator p, ∗p is the element to which it refers, ++p advances p to refer to the next element, and when p refers to a class with a member m, then p−>m is equivalent to (∗p).m . Adding elements to a list and removing elements from a list is easy: void f(const Entry& ee, list<Entry>::iterator p, list<Entry>::iterator q) { phone_book.insert(p,ee); // add ee before the element referred to by p phone_book.erase(q); // remove the element referred to by q } For a more complete description of insert() and erase(), see §31.3 .7 . These list examples could be written identically using vector and (surprisingly, unless you understand machine architecture) perform better with a small vector than with a small list. When all we want is a sequence of elements, we have a choice between using a vector and a list. Unless you have a reason not to, use a vector.Avector performs better for traversal (e.g ., find() and count()) and for sorting and searching (e.g ., sort() and binary_search()).
ptg10564057 100 A Tour of C++: Containers and Algorithms Chapter 4 4.4.3 map Writing code to look up a name in a list of (name,number) pairs is quite tedious. In addition, a lin- ear search is inefficient for all but the shortest lists. The standard library offers a search tree (a red- black tree) called map: 4 map: links key: value: links links links In other contexts, a map is known as an associative array or a dictionary. It is implemented as a bal- anced binary tree. The standard-library map (§31.4.3) is a container of pairs of values optimized for lookup. We can use the same initializer as for vector and list (§4.4 .1, §4.4 .2): map<string,int> phone_book { {"David Hume",123456}, {"Karl Popper",234567}, {"Bertrand Arthur William Russell",345678} }; When indexed by a value of its first type (called the key), a map returns the corresponding value of the second type (called the value or the mapped type). For example: int get_number(const string& s) { return phone_book[s]; } In other words, subscripting a map is essentially the lookup we called get_number().Ifakey isn’t found, it is entered into the map with a default value for its value. The default value for an integer type is 0; the value I just happened to choose represents an invalid telephone number. If we wanted to avoid entering invalid numbers into our phone book, we could use find() and insert() instead of [] (§31.4 .3 .1). 4.4.4 unordered_map The cost of a map lookup is O(log(n)) where n is the number of elements in the map. That’s pretty good. For example, for a map with 1,000,000 elements, we perform only about 20 comparisons and indirections to find an element. However, in many cases, we can do better by using a hashed lookup rather than comparison using an ordering function, such as <. The standard-library hashed
ptg10564057 Section 4.4 .4 unordered_map 101 containers are referred to as ‘‘unordered’’ because they don’t require an ordering function: rep unordered_map: hash table: For example, we can use an unordered_map from <unordered_map> for our phone book: unordered_map<string,int> phone_book { {"David Hume",123456}, {"Karl Popper",234567}, {"Bertrand Arthur William Russell",345678} }; As for a map, we can subscript an unordered_map: int get_number(const string& s) { return phone_book[s]; } The standard-library unordered_map provides a default hash function for strings. If necessary, you can provide your own (§31.4 .3 .4). 4.4.5 Container Overview The standard library provides some of the most general and useful container types to allow the pro- grammer to select a container that best serves the needs of an application: Standard Container Summary vector<T> A variable-size vector (§31.4) list<T> A doubly-linked list (§31.4 .2) forward_list<T> A singly-linked list (§31.4.2) deque<T> A double-ended queue (§31.2) set<T> A set (§31.4 .3) multiset<T> A set in which a value can occur many times (§31.4 .3) map<K,V> An associative array (§31.4 .3) multimap<K,V> A map in which a key can occur many times (§31.4 .3) unordered_map<K,V> A map using a hashed lookup (§31.4 .3.2) unordered_multimap<K,V> A multimap using a hashed lookup (§31.4 .3.2) unordered_set<T> A set using a hashed lookup (§31.4 .3 .2) unordered_multiset<T> A multiset using a hashed lookup (§31.4 .3 .2) The unordered containers are optimized for lookup with a key (often a string); in other words, they are implemented using hash tables.
ptg10564057 102 A Tour of C++: Containers and Algorithms Chapter 4 The standard containers are described in §31.4 . The containers are defined in namespace std and presented in headers <vector>, <list>, <map>, etc. (§4.1 .2, §30.2). In addition, the standard library provides container adaptors queue<T> (§31.5 .2), stack<T> (§31.5.1), deque<T> (§31.4), and priority_queue<T> (§31.5.3). The standard library also provides more specialized container-like types, such as a fixed-size array array<T,N> (§34.2 .1) and bitset<N> (§34.2 .2). The standard containers and their basic operations are designed to be similar from a notational point of view. Furthermore, the meanings of the operations are equivalent for the various contain- ers. Basic operations apply to every kind of container for which they make sense and can be effi- ciently implemented. For example: • begin() and end() give iterators to the first and one-beyond-the-last elements, respectively. • push_back() can be used (efficiently) to add elements to the end of a vector, forward_list, list, and other containers. • size() returns the number of elements. This notational and semantic uniformity enables programmers to provide new container types that can be used in a very similar manner to the standard ones. The range-checked vector, Vector (§2.3 .2, §2.4.3 .1), is an example of that. The uniformity of container interfaces also allows us to specify algorithms independently of individual container types. However, each has strengths and weaknesses. For example, subscripting and traversing a vector is cheap and easy. On the other hand, vector elements are moved when we insert or remove elements; list has exactly the opposite properties. Please note that a vector is usually more efficient than a list for short sequences of small elements (even for insert() and erase()). I recommend the standard-library vector as the default type for sequences of elements: you need a reason to choose another. 4.5 Algorithms A data structure, such as a list or a vector, is not very useful on its own. To use one, we need opera- tions for basic access such as adding and removing elements (as is provided for list and vector). Furthermore, we rarely just store objects in a container. We sort them, print them, extract subsets, remove elements, search for objects, etc. Consequently, the standard library provides the most common algorithms for containers in addition to providing the most common container types. For example, the following sorts a vector and places a copy of each unique vector element on a list: bool operator<(const Entry& x, const Entry& y) // less than { return x.name<y.name; // order Entrys by their names } void f(vector<Entry>& vec, list<Entry>& lst) { sort(vec.begin(),vec.end()); // use < for order unique_copy(vec.begin(),vec.end(),lst.begin()); // don’t copy adjacent equal elements } The standard algorithms are described in Chapter 32. They are expressed in terms of sequences of elements. A sequence is represented by a pair of iterators specifying the first element and the one- beyond-the-last element:
ptg10564057 Section 4.5 Algorithms 103 elements: begin() end() iterators: In the example, sort() sorts the sequence defined by the pair of iterators vec.begin() and vec.end() – which just happens to be all the elements of a vector. For writing (output), you need only to specify the first element to be written. If more than one element is written, the elements following that ini- tial element will be overwritten. Thus, to avoid errors, lst must have at least as many elements as there are unique values in vec. If we wanted to place the unique elements in a new container, we could have written: list<Entry> f(vector<Entry>& vec) { list<Entry> res; sort(vec.begin(),vec.end()); unique_copy(vec.begin(),vec.end(),back_inserter(res)); // append to res return res; } A back_inserter() adds elements at the end of a container, extending the container to make room for them (§33.2 .2). Thus, the standard containers plus back_inserter()s eliminate the need to use error- prone, explicit C-style memory management using realloc() (§31.5 .1). The standard-library list has a move constructor (§3.3 .2, §17.5 .2) that makes returning res by value efficient (even for listsof thousands of elements). If you find the pair-of-iterators style of code, such as sort(vec.begin(),vec.end()), tedious, you can define container versions of the algorithms and write sort(vec) (§4.5 .6). 4.5.1 Use of Iterators When you first encounter a container, a few iterators referring to useful elements can be obtained; begin() and end() are the best examples of this. In addition, many algorithms return iterators. For example, the standard algorithm find looks for a value in a sequence and returns an iterator to the element found: bool has_c(const string& s, char c) // does s contain the character c? { auto p = find(s.begin(),s.end(),c); if (p!=s.end()) return true; else return false; } Like many standard-library search algorithms, find returns end() to indicate ‘‘not found.’’ An equiv- alent, shorter, definition of has_c() is:
ptg10564057 104 A Tour of C++: Containers and Algorithms Chapter 4 bool has_c(const string& s, char c) // does s contain the character c? { return find(s.begin(),s.end(),c)!=s.end(); } A more interesting exercise would be to find the location of all occurrences of a character in a string. We can return the set of occurrences as a vector of string iterators. Returning a vector is efficient because of vector provides move semantics (§3.3 .1). Assuming that we would like to modify the locations found, we pass a non-const string: vector<string::iterator> find_all(string& s, char c) // find all occurrences of c in s { vector<string::iterator> res; for (auto p = s.begin(); p!=s.end(); ++p) if (∗p==c) res.push_back(p); return res; } We iterate through the string using a conventional loop, moving the iterator p forward one element at a time using ++ and looking at the elements using the dereference operator ∗. We could test find_all() like this: void test() { string m {"Mary had a little lamb"}; for (auto p : find_all(m,'a')) if (∗p!='a') cerr << "a bug!\n"; } That call of find_all() could be graphically represented like this: Mary had a little lamb m: find_all(m,’a’): Iterators and standard algorithms work equivalently on every standard container for which their use makes sense. Consequently, we could generalize find_all(): template<typename C, typename V> vector<typename C::iterator> find_all(C& c, V v) // find all occurrences of v in c { vector<typename C::iterator> res; for (auto p = c.begin(); p!=c.end(); ++p) if (∗p==v) res.push_back(p); return res; }
ptg10564057 Section 4.5 .1 Use of Iterators 105 The typename is needed to inform the compiler that C’s iterator is supposed to be a type and not a value of some type, say, the integer 7. We can hide this implementation detail by introducing a type alias (§3.4.5) for Iterator: template<typename T> using Iterator<T> = typename T::iterator; template<typename C, typename V> vector<Iterator<C>> find_all(C& c, V v) // find all occurrences of v in c { vector<Iterator<C>> res; for (auto p = c.begin(); p!=c.end(); ++p) if (∗p==v) res.push_back(p); return res; } We can now write: void test() { string m {"Mary had a little lamb"}; for (auto p : find_all(m,'a')) // p is a string::iterator if (∗p!='a') cerr << "string bug!\n"; list<double> ld {1.1, 2.2, 3.3, 1.1}; for (auto p : find_all(ld,1.1)) if (∗p!=1.1) cerr << "list bug!\n"; vector<string> vs { "red", "blue", "green", "green", "orange", "green" }; for (auto p : find_all(vs,"green")) if (∗p!="green") cerr << "vector bug!\n"; for (auto p : find_all(vs,"green")) ∗p = "vert"; } Iterators are used to separate algorithms and containers. An algorithm operates on its data through iterators and knows nothing about the container in which the elements are stored. Conversely, a container knows nothing about the algorithms operating on its elements; all it does is to supply iter- ators upon request (e.g ., begin() and end()). This model of separation between data storage and algorithm delivers very general and flexible software. 4.5.2 Iterator Types What are iterators really? Any particular iterator is an object of some type. There are, however, many different iterator types, because an iterator needs to hold the information necessary for doing
ptg10564057 106 A Tour of C++: Containers and Algorithms Chapter 4 its job for a particular container type. These iterator types can be as different as the containers and the specialized needs they serve. For example, a vector’s iterator could be an ordinary pointer, because a pointer is quite a reasonable way of referring to an element of a vector: P i e t H e i n vector: p iterator: Alternatively, a vector iterator could be implemented as a pointer to the vector plus an index: P i e t H e i n vector: (start == p, position == 3) iterator: Using such an iterator would allow range checking. A list iterator must be something more complicated than a simple pointer to an element because an element of a list in general does not know where the next element of that list is. Thus, a list iter- ator might be a pointer to a link: link link link link ... list: p iterator: P i e t elements: What is common for all iterators is their semantics and the naming of their operations. For exam- ple, applying ++ to any iterator yields an iterator that refers to the next element. Similarly, ∗ yields the element to which the iterator refers. In fact, any object that obeys a few simple rules like these is an iterator (§33.1 .4). Furthermore, users rarely need to know the type of a specific iterator; each container ‘‘knows’’ its iterator types and makes them available under the conventional names itera- tor and const_iterator. For example, list<Entry>::iterator is the general iterator type for list<Entry>. We rarely have to worry about the details of how that type is defined. 4.5.3 Stream Iterators Iterators are a general and useful concept for dealing with sequences of elements in containers. However, containers are not the only place where we find sequences of elements. For example, an input stream produces a sequence of values, and we write a sequence of values to an output stream. Consequently, the notion of iterators can be usefully applied to input and output. To make an ostream_iterator, we need to specify which stream will be used and the type of objects written to it. For example:
ptg10564057 Section 4.5 .3 Stream Iterators 107 ostream_iterator<string> oo {cout}; // write strings to cout The effect of assigning to ∗oo is to write the assigned value to cout. For example: int main() { ∗oo = "Hello, "; // meaning cout<<"Hello, " ++oo; ∗oo = "world!\n"; // meaning cout<<"world!\n" } This is yet another way of writing the canonical message to standard output. The ++oo is done to mimic writing into an array through a pointer. Similarly, an istream_iterator is something that allows us to treat an input stream as a read-only container. Again, we must specify the stream to be used and the type of values expected: istream_iterator<string> ii {cin}; Input iterators are used in pairs representing a sequence, so we must provide an istream_iterator to indicate the end of input. This is the default istream_iterator: istream_iterator<string> eos {}; Typically, istream_iterators and ostream_iterators are not used directly. Instead, they are provided as arguments to algorithms. For example, we can write a simple program to read a file, sort the words read, eliminate duplicates, and write the result to another file: int main() { string from, to; cin >> from >> to; // get source and target file names ifstream is {from}; // input stream for file "from" istream_iterator<string> ii {is}; // input iterator for stream istream_iterator<string> eos {}; // input sentinel ofstream os{to}; // output stream for file "to" ostream_iterator<string> oo {os,"\n"}; // output iterator for stream vector<string> b {ii,eos}; // b is a vector initialized from input [ii:eos) sort(b.begin(),b.end()); // sort the buffer unique_copy(b.begin(),b.end(),oo); // copy buffer to output, discard replicated values return !is.eof() || !os; // return error state (§2.2 .1, §38.3) } An ifstream is an istream that can be attached to a file, and an ofstream is an ostream that can be attached to a file. The ostream_iterator’s second argument is used to delimit output values. Actually, this program is longer than it needs to be. We read the strings into a vector, then we sort() them, and then we write them out, eliminating duplicates. A more elegant solution is not to
ptg10564057 108 A Tour of C++: Containers and Algorithms Chapter 4 store duplicates at all. This can be done by keeping the stringsinaset, which does not keep dupli- cates and keeps its elements in order (§31.4 .3). That way, we could replace the two lines using a vector with one using a set and replace unique_copy() with the simpler copy(): set<string> b {ii,eos}; // collect strings from input copy(b.begin(),b.end(),oo); // copy buffer to output We used the names ii, eos, and oo only once, so we could further reduce the size of the program: int main() { string from, to; cin >> from >> to; // get source and target file names ifstream is {from}; // input stream for file "from" ofstream os {to}; // output stream for file "to" set<string> b {istream_iterator<string>{is},istream_iterator<string>{}}; // read input copy(b.begin(),b.end(),ostream_iterator<string>{os,"\n"}); // copy to output return !is.eof() || !os; // return error state (§2.2 .1, §38.3) } It is a matter of taste and experience whether or not this last simplification improves readability. 4.5.4 Predicates In the examples above, the algorithms have simply ‘‘built in’’ the action to be done for each ele- ment of a sequence. However, we often want to make that action a parameter to the algorithm. For example, the find algorithm (§32.4) provides a convenient way of looking for a specific value. A more general variant looks for an element that fulfills a specified requirement, a predicate (§3.4 .2). For example, we might want to search a map for the first value larger than 42.Amap allows us to access its elements as a sequence of (key,value) pairs, so we can search a map<string,int>’s sequence for a pair<const string,int> where the int is greater than 42: void f(map<string,int>& m) { auto p = find_if(m.begin(),m.end(),Greater_than{42}); // ... } Here, Greater_than is a function object (§3.4 .3) holding the value (42) to be compared against: struct Greater_than { int val; Greater_than(int v) : val{v} { } bool operator()(const pair<string,int>& r) { return r.second>val; } }; Alternatively, we could use a lambda expression (§3.4 .3): int cxx = count_if(m.begin(), m.end(), [](const pair<string,int>& r) { return r.second>42; });
ptg10564057 Section 4.5 .4 Predicates 109 4.5.5 Algorithm Overview A general definition of an algorithm is ‘‘a finite set of rules which gives a sequence of operations for solving a specific set of problems [and] has five important features: Finiteness ... Definiteness ... Input ... Output ... Effectiveness’’ [Knuth,1968,§1.1]. In the context of the C++ standard library, an algorithm is a function template operating on sequences of elements. The standard library provides dozens of algorithms. The algorithms are defined in namespace std and presented in the <algorithm> header. These standard-library algorithms all take sequences as inputs (§4.5). A half-open sequence from b to e is referred to as [b:e). Here are a few I have found particularly useful: Selected Standard Algorithms p=find(b,e,x) p is the first p in [b:e) so that ∗p==x p=find_if(b,e,f) p is the first p in [b:e) so that f(∗p)==true n=count(b,e,x) n is the number of elements ∗q in [b:e) so that ∗q==x n=count_if(b,e,f) n is the number of elements ∗q in [b:e) so that f(∗q,x) replace(b,e,v,v2) Replace elements ∗q in [b:e) so that ∗q==v by v2 replace_if(b,e,f,v2) Replace elements ∗q in [b:e) so that f(∗q) by v2 p=copy(b,e,out) Copy [b:e)to[out:p) p=copy_if(b,e,out,f) Copy elements ∗q from [b:e) so that f(∗q) to [out:p) p=unique_copy(b,e,out) Copy [b:e)to[out:p); don’t copy adjacent duplicates sort(b,e) Sort elements of [b:e) using < as the sorting criterion sort(b,e,f) Sort elements of [b:e) using f as the sorting criterion (p1,p2)=equal_range(b,e,v) [p1:p2) is the subsequence of the sorted sequence [b:e) with the value v; basically a binary search for v p=merge(b,e,b2,e2,out) Merge two sorted sequences [b:e) and [b2:e2) into [out:p) These algorithms, and many more (see Chapter 32), can be applied to elements of containers, strings, and built-in arrays. 4.5.6 Container Algorithms A sequence is defined by a pair of iterators [begin:end). This is general and flexible, but most often, we apply an algorithm to a sequence that is the contents of a container. For example: sort(v.begin(),v.end()); Why don’t we just say sort(v)? We can easily provide that shorthand: namespace Estd { using namespace std; template<class C> void sort(C& c) { sort(c.begin(),c.end()); }
ptg10564057 110 A Tour of C++: Containers and Algorithms Chapter 4 template<class C, class Pred> void sort(C& c, Pred p) { sort(c.begin(),c.end(),p); } // ... } I put the container versions of sort() (and other algorithms) into their own namespace Estd (‘‘extended std’’) to avoid interfering with other programmers’ uses of namespace std. 4.6 Advice [1] Don’t reinvent the wheel; use libraries; §4.1 . [2] When you have a choice, prefer the standard library over other libraries; §4.1 . [3] Do not think that the standard library is ideal for everything; §4.1. [4] Remember to #include the headers for the facilities you use; §4.1 .2 . [5] Remember that standard-library facilities are defined in namespace std; §4.1 .2 . [6] Prefer strings over C-style strings (a char∗; §2.2.5); §4.2, §4.3 .2. [7] iostreams are type sensitive, type-safe, and extensible; §4.3. [8] Prefer vector<T>, map<K,T>, and unordered_map<K,T> over T[]; §4.4 . [9] Know your standard containers and their tradeoffs; §4.4 . [10] Use vector as your default container; §4.4 .1. [11] Prefer compact data structures; §4.4 .1 .1 . [12] If in doubt, use a range-checked vector (such as Vec ); §4.4 .1 .2 . [13] Use push_back() or back_inserter() to add elements to a container; §4.4.1, §4.5. [14] Use push_back() on a vector rather than realloc() on an array; §4.5 . [15] Catch common exceptions in main(); §4.4 .1 .2 . [16] Know your standard algorithms and prefer them over handwritten loops; §4.5 .5 . [17] If iterator use gets tedious, define container algorithms; §4.5.6 .
ptg10564057 5 A Tour of C++: Concurrency and Utilities When you wish to instruct, be brief. – Cicero • Introduction • Resource Management unique_ptr and shared_ptr • Concurrency Tasks and threads; Passing Arguments; Returning Results; Sharing Data; Communicating Tasks • Small Utility Components Time; Type Functions; pair and tuple • Regular Expressions • Math Mathematical Functions and Algorithms; Complex Numbers; Random Numbers; Vector Arithmetic; Numeric Limits • Advice 5.1 Introduction From an end-user’s perspective, the ideal standard library would provide components directly sup- porting essentially every need. For a given application domain, a huge commercial library can come close to that ideal. However, that is not what the C++ standard library is trying to do. A manageable, universally available, library cannot be everything to everybody. Instead, the C++ standard library aims to provide components that are useful to most people in most application areas. That is, it aims to serve the intersection of all needs rather than their union. In addition, sup- port for a few widely important application areas, such as mathematical computation and text manipulation, have crept in.
ptg10564057 112 A Tour of C++: Concurrency and Utilities Chapter 5 5.2 Resource Management One of the key tasks of any nontrivial program is to manage resources. A resource is something that must be acquired and later (explicitly or implicitly) released. Examples are memory, locks, sockets, thread handles, and file handles. For a long-running program, failing to release a resource in a timely manner (‘‘a leak’’) can cause serious performance degradation and possibly even a mis- erable crash. Even for short programs, a leak can become an embarrassment, say by a resource shortage increasing the run time by orders of magnitude. The standard library components are designed not to leak resources. To do this, they rely on the basic language support for resource management using constructor/destructor pairs to ensure that a resource doesn’t outlive an object responsible for it. The use of a constructor/destructor pair in Vector to manage the lifetime of its elements is an example (§3.2 .1 .2) and all standard-library con- tainers are implemented in similar ways. Importantly, this approach interacts correctly with error handling using exceptions. For example, the technique is used for the standard-library lock classes: mutex m; // used to protect access to shared data // ... void f() { unique_lock<mutex> lck {m}; // acquire the mutex m // ... manipulate shared data ... } A thread will not proceed until lck’s constructor has acquired its mutex, m (§5.3 .4). The corre- sponding destructor releases the resource. So, in this example, unique_lock’s destructor releases the mutex when the thread of control leaves f() (through a return, by ‘‘falling off the end of the func- tion,’’ or through an exception throw). This is an application of the ‘‘Resource Acquisition Is Initialization’’ technique (RAII; §3.2 .1 .2, §13.3). This technique is fundamental to the idiomatic handling of resources in C++. Containers (such as vector and map), string, and iostream manage their resources (such as file handles and buf- fers) similarly. 5.2.1 unique_ptr and shared_ptr The examples so far take care of objects defined in a scope, releasing the resources they acquire at the exit from the scope, but what about objects allocated on the free store? In <memory>, the stan- dard library provides two ‘‘smart pointers’’ to help manage objects on the free store: [1] unique_ptr to represent unique ownership (§34.3 .1) [2] shared_ptr to represent shared ownership (§34.3.2) The most basic use of these ‘‘smart pointers’’ is to prevent memory leaks caused by careless pro- gramming. For example: void f(int i, int j) // X* vs. unique_ptr<X> { X∗p=newX; // allocate a new X unique_ptr<X> sp {new X}; // allocate a new X and give its pointer to unique_ptr // ...
ptg10564057 Section 5.2 .1 unique_ptr and shared_ptr 113 if (i<99) throw Z{}; // may throw an exception if (j<77) return; // may return "early" p−>do_something(); // may throw an exception sp−>do_something(); // may throw an exception // ... delete p; // destroy *p } Here, we ‘‘forgot’’ to delete p if i<99 or if j<77. On the other hand, unique_ptr ensures that its object is properly destroyed whichever way we exit f() (by throwing an exception, by executing return,or by ‘‘falling off the end’’). Ironically, we could have solved the problem simply by not using a pointer and not using new: void f(int i, int j) // use a local variable { Xx; // ... } Unfortunately, overuse of new (and of pointers and references) seems to be an increasing problem. However, when you really need the semantics of pointers, unique_ptr is a very lightweight mechanism with no space or time overhead compared to correct use of a built-in pointer. Its further uses include passing free-store allocated objects in and out of functions: unique_ptr<X> make_X(int i) // make an X and immediately give it to a unique_ptr { // ... check i, etc. ... return unique_ptr<X>{new X{i}}; } A unique_ptr is a handle to an individual object (or an array) in much the same way that a vector is a handle to a sequence of objects. Both control the lifetime of other objects (using RAII) and both rely on move semantics to make return simple and efficient. The shared_ptr is similar to unique_ptr except that shared_ptrs are copied rather than moved. The shared_ptrs for an object share ownership of an object and that object is destroyed when the last of its shared_ptrs is destroyed. For example: void f(shared_ptr<fstream>); void g(shared_ptr<fstream>); void user(const string& name, ios_base::openmode mode) { shared_ptr<fstream> fp {new fstream(name,mode)}; if (!∗fp) throw No_file{}; // make sure the file was properly opened f(fp); g(fp); // ... }
ptg10564057 114 A Tour of C++: Concurrency and Utilities Chapter 5 Now, the file opened by fp’s constructor will be closed by the last function to (explicitly or implic- itly) destroy a copy of fp. Note that f() or g() may spawn a task holding a copy of fp or in some other way store a copy that outlives user(). Thus, shared_ptr provides a form of garbage collection that respects the destructor-based resource management of the memory-managed objects. This is neither cost free nor exorbitantly expensive, but does make the lifetime of the shared object hard to predict. Use shared_ptr only if you actually need shared ownership. Given unique_ptr and shared_ptr, we can implement a complete ‘‘no naked new’’ policy (§3.2 .1 .2) for many programs. However, these ‘‘smart pointers’’ are still conceptually pointers and therefore only my second choice for resource management – after containers and other types that manage their resources at a higher conceptual level. In particular, shared_ptrs do not in themselves provide any rules for which of their owners can read and/or write the shared object. Data races (§41.2.4) and other forms of confusion are not addressed simply by eliminating the resource man- agement issues. Where do we use ‘‘smart pointers’’ (such as unique_ptr) rather than resource handles with oper- ations designed specifically for the resource (such as vector or thread)? Unsurprisingly, the answer is ‘‘when we need pointer semantics.’’ • When we share an object, we need pointers (or references) to refer to the shared object, so a shared_ptr becomes the obvious choice (unless there is an obvious single owner). • When we refer to a polymorphic object, we need a pointer (or a reference) because we don’t know the exact type of the object referred to or even its size), so a unique_ptr becomes the obvious choice. • A shared polymorphic object typically requires shared_ptrs. We d o not need to use a pointer to return a collection of objects from a function; a container that is a resource handle will do that simply and efficiently (§3.3 .2). 5.3 Concurrency Concurrency – the execution of several tasks simultaneously – is widely used to improve through- put (by using several processors for a single computation) or to improve responsiveness (by allow- ing one part of a program to progress while another is waiting for a response). All modern pro- gramming languages provide support for this. The support provided by the C++ standard library is a portable and type-safe variant of what has been used in C++ for more than 20 years and is almost universally supported by modern hardware. The standard-library support is primarily aimed at sup- porting systems-level concurrency rather than directly providing sophisticated higher-level concur- rency models; those can be supplied as libraries built using the standard-library facilities. The standard library directly supports concurrent execution of multiple threads in a single address space. To allow that, C++ provides a suitable memory model (§41.2) and a set of atomic operations (§41.3). However, most users will see concurrency only in terms of the standard library and libraries built on top of that. This section briefly gives examples of the main standard-library concurrency support facilities: threads, mutexes, lock() operations, packaged_tasks, and futures. These features are built directly upon what operating systems offer and do not incur performance penalties compared with those.
ptg10564057 Section 5.3 .1 Tasks and threads 115 5.3.1 Tasks and threads We call a computation that can potentially be executed concurrently with other computations a task. A thread is the system-level representation of a task in a program. A task to be executed concur- rently with other tasks is launched by constructing a std::thread (found in <thread>) with the task as its argument. A task is a function or a function object: void f(); // function struct F { // function object void operator()(); // F’s call operator (§3.4 .3) }; void user() { thread t1 {f}; // f() executes in separate thread thread t2 {F()}; // F()() executes in separate thread t1.join(); // wait for t1 t2.join(); // wait for t2 } The join()s ensure that we don’t exit user() until the threads have completed. To ‘‘join’’ means to ‘‘wait for the thread to terminate.’’ Threads of a program share a single address space. In this, threads differ from processes, which generally do not directly share data. Since threads share an address space, they can communicate through shared objects (§5.3 .4). Such communication is typically controlled by locks or other mechanisms to prevent data races (uncontrolled concurrent access to a variable). Programming concurrent tasks can be very tricky. Consider possible implementations of the tasks f (a function) and F (a function object): void f() { cout << "Hello "; } struct F { void operator()() { cout << "Parallel World!\n"; } }; This is an example of a bad error: Here, f and F() each use the object cout without any form of syn- chronization. The resulting output would be unpredictable and could vary between different execu- tions of the program because the order of execution of the individual operations in the two tasks is not defined. The program may produce ‘‘odd’’ output, such as PaHerallllel o World! When defining tasks of a concurrent program, our aim is to keep tasks completely separate except where they communicate in simple and obvious ways. The simplest way of thinking of a concur- rent task is as a function that happens to run concurrently with its caller. For that to work, we just have to pass arguments, get a result back, and make sure that there is no use of shared data in between (no data races).
ptg10564057 116 A Tour of C++: Concurrency and Utilities Chapter 5 5.3.2 Passing Arguments Typically, a task needs data to work upon. We can easily pass data (or pointers or references to the data) as arguments. Consider: void f(vector<double>& v); // function do something with v struct F { // function object: do something with v vector<double>& v; F(vector<double>& vv) :v{vv} { } void operator()(); // application operator; §3.4.3 }; int main() { vector<double> some_vec {1,2,3,4,5,6,7,8,9}; vector<double> vec2 {10,11,12,13,14}; thread t1 {f,some_vec}; // f(some_vec) executes in a separate thread thread t2 {F{vec2}}; // F(vec2)() executes in a separate thread t1.join(); t2.join(); } Obviously, F{vec2} saves a reference to the argument vector in F. F can now use that array and hopefully no other task accesses vec2 while F is executing. Passing vec2 by value would eliminate that risk. The initialization with {f,some_vec} uses a thread variadic template constructor that can accept an arbitrary sequence of arguments (§28.6). The compiler checks that the first argument can be invoked given the following arguments and builds the necessary function object to pass to the thread. Thus, if F::operator()() and f() perform the same algorithm, the handling of the two tasks are roughly equivalent: in both cases, a function object is constructed for the thread to execute. 5.3.3 Returning Results In the example in §5.3.2, I pass the arguments by non-const reference. I only do that if I expect the task to modify the value of the data referred to (§7.7). That’s a somewhat sneaky, but not uncom- mon, way of returning a result. A less obscure technique is to pass the input data by const refer- ence and to pass the location of a place to deposit the result as a separate argument: void f(const vector<double>& v, double∗ res);// take input from v; place result in *res class F { public: F(const vector<double>& vv, double∗ p) :v{vv}, res{p} { } void operator()(); // place result in *res
ptg10564057 Section 5.3 .3 Returning Results 117 private: const vector<double>& v; // source of input double∗ res; // target for output }; int main() { vector<double> some_vec; vector<double> vec2; // ... double res1; double res2; thread t1 {f,some_vec,&res1}; // f(some_vec,&res1) executes in a separate thread thread t2 {F{vec2,&res2}}; // F{vec2,&res2}() executes in a separate thread t1.join(); t2.join(); cout<<res1<<''<<res2<<'\n'; } I don’t consider returning results through arguments particularly elegant, so I return to this topic in §5.3.5.1. 5.3.4 Sharing Data Sometimes tasks need to share data. In that case, the access has to be synchronized so that at most one task at a time has access. Experienced programmers will recognize this as a simplification (e.g., there is no problem with many tasks simultaneously reading immutable data), but consider how to ensure that at most one task at a time has access to a given set of objects. The fundamental element of the solution is a mutex, a ‘‘mutual exclusion object.’’ A thread acquires a mutex using a lock() operation: mutex m; // controlling mutex int sh; // shared data void f() { unique_lock<mutex> lck {m}; // acquire mutex sh+=7; // manipulate shared data }/ / release mutex implicitly The unique_lock’s constructor acquires the mutex (through a call m.lock()). If another thread has already acquired the mutex, the thread waits (‘‘blocks’’) until the other thread completes its access. Once a thread has completed its access to the shared data, the unique_lock releases the mutex (with a call m.unlock()). The mutual exclusion and locking facilities are found in <mutex>.
ptg10564057 118 A Tour of C++: Concurrency and Utilities Chapter 5 The correspondence between the shared data and a mutex is conventional: the programmer simply has to know which mutex is supposed to correspond to which data. Obviously, this is error-prone, and equally obviously we try to make the correspondence clear through various language means. For example: class Record { public: mutex rm; // ... }; It doesn’t take a genius to guess that for a Record called rec, rec.rm is a mutex that you are supposed to acquire before accessing the other data of rec, though a comment or a better name might have helped a reader. It is not uncommon to need to simultaneously access several resources to perform some action. This can lead to deadlock. For example, if thread1 acquires mutex1 and then tries to acquire mutex2 while thread2 acquires mutex2 and then tries to acquire mutex1, then neither task will ever proceed further. The standard library offers help in the form of an operation for acquiring several locks simultaneously: void f() { // ... unique_lock<mutex> lck1 {m1,defer_lock}; // defer_lock: don’t yet try to acquire the mutex unique_lock<mutex> lck2 {m2,defer_lock}; unique_lock<mutex> lck3 {m3,defer_lock}; // ... lock(lck1,lck2,lck3); // acquire all three locks // ... manipulate shared data ... }//implicitly release all mutexes This lock() will only proceed after acquiring all its mutex arguments and will never block (‘‘go to sleep’’) while holding a mutex. The destructors for the individual unique_locks ensure that the mutexes are released when a thread leaves the scope. Communicating through shared data is pretty low level. In particular, the programmer has to devise ways of knowing what work has and has not been done by various tasks. In that regard, use of shared data is inferior to the notion of call and return. On the other hand, some people are con- vinced that sharing must be more efficient than copying arguments and returns. That can indeed be so when large amounts of data are involved, but locking and unlocking are relatively expensive operations. On the other hand, modern machines are very good at copying data, especially compact data, such as vector elements. So don’t choose shared data for communication because of ‘‘effi- ciency’’ without thought and preferably not without measurement. 5.3 .4.1 Waiting for Events Sometimes, a thread needs to wait for some kind of external event, such as another thread complet- ing a task or a certain amount of time having passed. The simplest ‘‘event’’ is simply time passing. Consider:
ptg10564057 Section 5.3 .4 .1 Waiting for Events 119 using namespace std::chrono; // see §35.2 auto t0 = high_resolution_clock::now(); this_thread::sleep_for(milliseconds{20}); auto t1 = high_resolution_clock::now(); cout << duration_cast<nanoseconds>(t1−t0).count() << " nanoseconds passed\n"; Note that I didn’t even have to launch a thread; by default, this_thread refers to the one and only thread (§42.2 .6). I used duration_cast to adjust the clock’s units to the nanoseconds I wanted. See §5.4.1 and §35.2 before trying anything more complicated than this with time. The time facilities are found in <chrono>. The basic support for communicating using external events is provided by condition_variables found in <condition_variable> (§42.3 .4). A condition_variable is a mechanism allowing one thread to wait for another. In particular, it allows a thread to wait for some condition (often called an event) to occur as the result of work done by other threads. Consider the classical example of two threads communicating by passing messages through a queue. For simplicity, I declare the queue and the mechanism for avoiding race conditions on that queue global to the producer and consumer: class Message { // object to be communicated // ... }; queue<Message> mqueue; // the queue of messages condition_variable mcond; // the variable communicating events mutex mmutex; // the locking mechanism The types queue, condition_variable, and mutex are provided by the standard library. The consumer() reads and processes Messages: void consumer() { while(true) { unique_lock<mutex> lck{mmutex}; // acquire mmutex while (mcond.wait(lck)) /* do nothing */; // release lck and wait; // re-acquire lck upon wakeup auto m = mqueue.front(); // get the message mqueue.pop(); lck.unlock(); // release lck // ... process m ... } } Here, I explicitly protect the operations on the queue and on the condition_variable with a unique_lock on the mutex. Waiting on condition_variable releases its lock argument until the wait is over (so that the queue is non-empty) and then reacquires it. The corresponding producer looks like this:
ptg10564057 120 A Tour of C++: Concurrency and Utilities Chapter 5 void producer() { while(true) { Message m; // ... fill the message ... unique_lock<mutex> lck {mmutex}; // protect operations mqueue.push(m); mcond.notify_one(); // notify }/ / release lock (at end of scope) } Using condition_variables supports many forms of elegant and efficient sharing, but can be rather tricky (§42.3.4). 5.3.5 Communicating Tasks The standard library provides a few facilities to allow programmers to operate at the conceptual level of tasks (work to potentially be done concurrently) rather than directly at the lower level of threads and locks: [1] future and promise for returning a value from a task spawned on a separate thread [2] packaged_task to help launch tasks and connect up the mechanisms for returning a result [3] async() for launching of a task in a manner very similar to calling a function. These facilities are found in <future>. 5.3 .5.1 future and promise The important point about future and promise is that they enable a transfer of a value between two tasks without explicit use of a lock; ‘‘the system’’ implements the transfer efficiently. The basic idea is simple: When a task wants to pass a value to another, it puts the value into a promise. Some- how, the implementation makes that value appear in the corresponding future, from which it can be read (typically by the launcher of the task). We can represent this graphically: future promise value task1: task2: get() set_value() set_exception() If we have a future<X> called fx,wecanget() a value of type X from it: Xv=fx.get(); // if necessary, wait for the value to get computed If the value isn’t there yet, our thread is blocked until it arrives. If the value couldn’t be computed, get() might throw an exception (from the system or transmitted from the task from which we were trying to get() the value).
ptg10564057 Section 5.3 .5 .1 future and promise 121 The main purpose of a promise is to provide simple ‘‘put’’ operations (called set_value() and set_exception()) to match future’s get(). The names ‘‘future’’ and ‘‘promise’’ are historical; please don’t blame me. They are yet another fertile source of puns. If you have a promise and need to send a result of type X to a future, you can do one of two things: pass a value or pass an exception. For example: void f(promise<X>& px) // a task: place the result in px { // ... try { X res; // ... compute a value for res ... px.set_value(res); } catch (...) { // oops: couldn’t compute res // pass the exception to the future’s thread: px.set_exception(current_exception()); } } The current_exception() refers to the caught exception (§30.4.1 .2). To deal with an exception transmitted through a future, the caller of get() must be prepared to catch it somewhere. For example: void g(future<X>& fx) // a task: get the result from fx { // ... try { Xv=fx.get(); // if necessary, wait for the value to get computed //...usev... } catch (...) { // oops: someone couldn’t compute v // ... handle error ... } } 5.3 .5.2 packaged_task How do we get a future into the task that needs a result and the corresponding promise into the thread that should produce that result? The packaged_task type is provided to simplify setting up tasks connected with futures and promises to be run on threads. A packaged_task provides wrapper code to put the return value or exception from the task into a promise (like the code shown in §5.3 .5 .1). If you ask it by calling get_future,apackaged_task will give you the future corresponding to its promise. For example, we can set up two tasks to each add half of the elements of a vector<double> using the standard-library accumulate() (§3.4 .2, §40.6):
ptg10564057 122 A Tour of C++: Concurrency and Utilities Chapter 5 double accum(double∗ beg, double ∗ end, double init) // compute the sum of [beg:end) starting with the initial value init { return accumulate(beg,end,init); } double comp2(vector<double>& v) { using Task_type = double(double∗,double∗,double); // type of task packaged_task<Task_type> pt0 {accum}; // package the task (i.e., accum) packaged_task<Task_type> pt1 {accum}; future<double> f0 {pt0.get_future()}; // get hold of pt0’s future future<double> f1 {pt1.get_future()}; // get hold of pt1’s future double∗ first = &v[0]; thread t1 {move(pt0),first,first+v.size()/2,0}; // start a thread for pt0 thread t2 {move(pt1),first+v.size()/2,first+v.size(),0}; // start a thread for pt1 // ... return f0.get()+f1.get(); // get the results } The packaged_task template takes the type of the task as its template argument (here Task_type,an alias for double(double∗,double∗,double)) and the task as its constructor argument (here, accum). The move() operations are needed because a packaged_task cannot be copied. Please note the absence of explicit mention of locks in this code: we are able to concentrate on tasks to be done, rather than on the mechanisms used to manage their communication. The two tasks will be run on separate threads and thus potentially in parallel. 5.3 .5.3 async() The line of thinking I have pursued in this chapter is the one I believe to be the simplest yet still among the most powerful: Treat a task as a function that may happen to run concurrently with other tasks. It is far from the only model supported by the C++ standard library, but it serves well for a wide range of needs. More subtle and tricky models, e.g ., styles of programming relying on shared memory, can be used as needed. To launch tasks to potentially run asynchronously, we can use async(): double comp4(vector<double>& v) // spawn many tasks if v is large enough { if (v.size()<10000) return accum(v.begin(),v.end(),0.0); auto v0 = &v[0]; auto sz = v.size();
ptg10564057 Section 5.3 .5 .3 async() 123 auto f0 = async(accum,v0,v0+sz/4,0.0); // first quarter auto f1 = async(accum,v0+sz/4,v0+sz/2,0.0); // second quarter auto f2 = async(accum,v0+sz/2,v0+sz∗3/4,0.0); // third quarter auto f3 = async(accum,v0+sz∗3/4,v0+sz,0.0); // fourth quarter return f0.get()+f1.get()+f2.get()+f3.get(); // collect and combine the results } Basically, async() separates the ‘‘call part’’ of a function call from the ‘‘get the result part,’’ and sep- arates both from the actual execution of the task. Using async(), you don’t have to think about threads and locks. Instead, you think just in terms of tasks that potentially compute their results asynchronously. There is an obvious limitation: Don’t even think of using async() for tasks that share resources needing locking – with async() you don’t even know how many threads will be used because that’s up to async() to decide based on what it knows about the system resources available at the time of a call. For example, async() may check whether any idle cores (processors) are avail- able before deciding how many threads to use. Please note that async() is not just a mechanism specialized for parallel computation for increased performance. For example, it can also be used to spawn a task for getting information from a user, leaving the ‘‘main program’’ active with something else (§42.4 .6). 5.4 Small Utility Components Not all standard-library components come as part of obviously labeled facilities, such as ‘‘contain- ers’’ or ‘‘I/O.’’ This section gives a few examples of small, widely useful components: • clock and duration for measuring time. • Type functions, such as iterator_traits and is_arithmetic, for gaining information about types. • pair and tuple for representing small potentially heterogeneous sets of values. The point here is that a function or a type need not be complicated or closely tied to a mass of other functions and types to be useful. Such library components mostly act as building blocks for more powerful library facilities, including other components of the standard library. 5.4.1 Time The standard library provides facilities for dealing with time. For example, here is the basic way of timing something: using namespace std::chrono; // see §35.2 auto t0 = high_resolution_clock::now(); do_work(); auto t1 = high_resolution_clock::now(); cout << duration_cast<milliseconds>(t1−t0).count() << "msec\n"; The clock returns a time_point (a point in time). Subtracting two time_points gives a duration (a period of time). Various clocks give their results in various units of time (the clock I used measures nanoseconds), so it is usually a good idea to convert a duration into a known unit. That’s what dura- tion_cast does.
ptg10564057 124 A Tour of C++: Concurrency and Utilities Chapter 5 The standard-library facilities for dealing with time are found in the subnamespace std::chrono in <chrono> (§35.2). Don’t make statements about ‘‘efficiency’’ of code without first doing time measurements. Guesses about performance are most unreliable. 5.4.2 Type Functions A type function is a function that is evaluated at compile-time given a type as its argument or returning a type. The standard library provides a variety of type functions to help library imple- menters and programmers in general to write code that take advantage of aspects of the language, the standard library, and code in general. For numerical types, numeric_limits from <limits> presents a variety of useful information (§5.6 .5). For example: constexpr float min = numeric_limits<float>::min(); // smallest positive float (§40.2) Similarly, object sizes can be found by the built-in sizeof operator (§2.2 .2). For example: constexpr int szi = sizeof(int); // the number of bytes in an int Such type functions are part of C++’s mechanisms for compile-time computation that allow tighter type checking and better performance than would otherwise have been possible. Use of such fea- tures is often called metaprogramming or (when templates are involved) template metaprogram- ming (Chapter 28). Here, I just present two facilities provided by the standard library: iterator_traits (§5.4 .2 .1) and type predicates (§5.4 .2 .2). 5.4 .2.1 iterator_traits The standard-library sort() takes a pair of iterators supposed to define a sequence (§4.5). Further- more, those iterators must offer random access to that sequence, that is, they must be random- access iterators. Some containers, such as forward_list, do not offer that. In particular, a for- ward_list is a singly-linked list so subscripting would be expensive and there is no reasonable way to refer back to a previous element. However, like most containers, forward_list offers forward iter- ators that can be used to traverse the sequence by algorithms and for-statements (§33.1 .1). The standard library provides a mechanism, iterator_traits that allows us to check which kind of iterator is supported. Given that, we can improve the range sort() from §4.5.6 to accept either a vector or a forward_list. For example: void test(vector<string>& v, forward_list<int>& lst) { sort(v); // sort the vector sort(lst); // sort the singly-linked list } The techniques needed to make that work are generally useful. First, I write two helper functions that take an extra argument indicating whether they are to be used for random-access iterators or forward iterators. The version taking random-access iterator arguments is trivial:
ptg10564057 Section 5.4 .2 .1 iterator_traits 125 template<typename Ran> // for random-access iterators void sort_helper(Ran beg, Ran end, random_access _iterator_tag) // we can subscript into [beg:end) { sort(beg,end); // just sort it } The version for forward iterators is almost as simple; just copy the list into a vector, sort, and copy back again: template<typename For> // for forward iterators void sort_helper(For beg, For end, forward_iterator_tag) // we can traverse [beg:end) { vector<decltype(∗beg)> v {beg,end}; // initialize a vector from [beg:end) sort(v.begin(),v.end()); copy(v.begin(),v.end(),beg); // copy the elements back } The decltype() is a built-in type function that returns the declared type of its argument (§6.3 .6 .3). Thus, v is a vector<X> where X is the element type of the input sequence. The real ‘‘type magic’’ is in the selection of helper functions: template<typname C> void sort(C& c) { using Iter = Iterator_type<C>; sort_helper(c.begin(),c.end(),Iterator_category<Iter>{}); } Here, I use two type functions: Iterator_type<C> returns the iterator type of C (that is, C::iterator) and then Iterator_category<Iter>{} constructs a ‘‘tag’’ value indicating the kind of iterator provided: • std::random_access _iterator_tag if C’s iterator supports random access. • std::forward_iterator_tag if C’s iterator supports forward iteration. Given that, we can select between the two sorting algorithms at compile time. This technique, called tag dispatch is one of several used in the standard library and elsewhere to improve flexibil- ity and performance. The standard-library support for techniques for using iterators, such as tag dispatch, comes in the form of a simple class template iterator_traits from <iterator> (§33.1 .3). This allows simple defi- nitions of the type functions used in sort(): template<typename C> using Iterator_type = typename C::iterator; // C’s iterator type template<typename Iter> using Iterator_category = typename std::iterator_traits<Iter>::iterator_category; // Iter’s category If you don’t want to know what kind of ‘‘compile-time type magic’’ is used to provide the standard- library features, you are free to ignore facilities such as iterator_traits. But then you can’t use the techniques they support to improve your own code.
ptg10564057 126 A Tour of C++: Concurrency and Utilities Chapter 5 5.4 .2.2 Type Predicates A standard-library type predicate is a simple type function that answers a fundamental question about types. For example: bool b1 = Is_arithmetic<int>(); // yes, int is an arithmetic type bool b2 = Is_arithmetic<string>(); // no, std::string is not an arithmetic type These predicates are found in <type_traits> and described in §35.4 .1 . Other examples are is_class, is_pod, is_literal_type, has_virtual_destructor, and is_base_of. They are most useful when we write templates. For example: template<typename Scalar> class complex { Scalar re, im; public: static_assert(Is_arithmetic<Scalar>(), "Sorry, I only support complex of arithmetic types"); // ... }; To improve readability compared to using the standard library directly, I defined a type function: template<typename T> constexpr bool Is_arithmetic() { return std::is_arithmetic<T>::value ; } Older programs use ::value directly instead of (), but I consider that quite ugly and it exposes imple- mentation details. 5.4.3 pair and tuple Often, we need some data that is just data; that is, a collection of values, rather than an object of a class with a well-defined semantics and an invariant for its value (§2.4 .3 .2, §13.4). In such cases, we could define a simple struct with an appropriate set of appropriately named members. Alterna- tively, we could let the standard library write the definition for us. For example, the standard- library algorithm equal_range (§32.6 .1) returns a pair of iterators specifying a sub-sequence meeting a predicate: template<typename Forward_iterator, typename T, typename Compare> pair<Forward_iterator,Forward_iterator> equal_range(Forward_iterator first, Forward_iterator last, const T& val, Compare cmp); Given a sorted sequence [first:last), equal_range() will return the pair representing the subsequence that matches the predicate cmp. We can use that to search in a sorted sequence of Records: auto rec_eq = [](const Record& r1, const Record& r2) { return r1.name<r2.name;};// compare names void f(const vector<Record>& v) // assume that v is sorted on its "name" field { auto er = equal_range(v.begin(),v.end(),Record{"Reg"},rec_eq);
ptg10564057 Section 5.4 .3 pair and tuple 127 for (auto p = er.first; p!=er.second; ++p) // print all equal records cout << ∗p; // assume that << is defined for Record } The first member of a pair is called first and the second member is called second. This naming is not particularly creative and may look a bit odd at first, but such consistent naming is a boon when we want to write generic code. The standard-library pair (from <utility>) is quite frequently used in the standard library and elsewhere. A pair provides operators, such as =, ==, and <, if its elements do. The make_pair() func- tion makes it easy to create a pair without explicitly mentioning its type (§34.2 .4 .1). For example: void f(vector<string>& v) { auto pp = make_pair(v.begin(),2); // pp is a pair<vector<string>::iterator,int> // ... } If you need more than two elements (or less), you can use tuple (from <utility>; §34.2 .4 .2). A tuple is a heterogeneous sequence of elements; for example: tuple<string,int,double> t2("Sild",123, 3.14); // the type is explicitly specified auto t = make_tuple(string("Herring"),10, 1.23); // the type is deduced // t is a tuple<string,int,double> string s = get<0>(t); // get first element of tuple int x = get<1>(t); double d = get<2>(t); The elements of a tuple are numbered (starting with zero), rather than named the way elements of pairs are (first and second). To get compile-time selection of elements, I must unfortunately use the ugly get<1>(t), rather than get(t,1) or t[1] (§28.5 .2). Like pairs, tuples can be assigned and compared if their elements can be. A pair is common in interfaces because often we want to return more than one value, such as a result and an indicator of the quality of that result. It is less common to need three or more parts to a result, so tuples are more often found in the implementations of generic algorithms. 5.5 Regular Expressions Regular expressions are a powerful tool for text processing. They provide a way to simply and tersely describe patterns in text (e.g ., a U.S . ZIP code such as TX 77845, or an ISO-style date, such as 2009−06 −07) and to efficiently find such patterns in text. In <regex>, the standard library provides support for regular expressions in the form of the std::regex class and its supporting functions. To give a taste of the style of the regex library, let us define and print a pattern: regex pat (R"(\w{2}\s∗\d{5}(−\d{4})?)"); // ZIP code pattern: XXddddd-dddd and variants cout << "pattern: " << pat << '\n';
ptg10564057 128 A Tour of C++: Concurrency and Utilities Chapter 5 People who have used regular expressions in just about any language will find \w{2}\s∗\d{5}(−\d{4})? familiar. It specifies a pattern starting with two letters \w{2} optionally followed by some space \s∗ followed by five digits \d{5} and optionally followed by a dash and four digits −\d{4}. If you are not familiar with regular expressions, this may be a good time to learn about them ([Stroustrup,2009], [Maddock,2009], [Friedl,1997]). Regular expressions are summarized in §37.1 .1 . To express the pattern, I use a raw string literal (§7.3 .2.1) starting with R"( and terminated by )". This allows backslashes and quotes to be used directly in the string. The simplest way of using a pattern is to search for it in a stream: int lineno = 0; for (string line; getline(cin,line);) { // read into line buffer ++lineno; smatch matches; // matched strings go here if (regex_search(line,matches,pat)) // search for pat in line cout << lineno << ": " << matches[0] << '\n'; } The regex_search(line,matches,pat) searches the line for anything that matches the regular expression stored in pat and if it finds any matches, it stores them in matches. If no match was found, regex_search(line,matches,pat) returns false. The matches variable is of type smatch. The ‘‘s’’ stands for ‘‘sub’’ and an smatch is a vector of sub-matches. The first element, here matches[0],is the complete match. For a more complete description see Chapter 37. 5.6 Math C++ wasn’t designed primarily with numerical computation in mind. However, C++ is heavily used for numerical computation and the standard library reflects that. 5.6.1 Mathematical Functions and Algorithms In <cmath>, we find the ‘‘usual mathematical functions,’’ such as sqrt(), log(), and sin() for argu- ments of type float, double, and long double (§40.3). Complex number versions of these functions are found in <complex> (§40.4). In <numeric>, we find a small set of generalized numerical algorithms, such as accumulate().For example: void f() { list<double> lst {1, 2, 3, 4, 5, 9999.99999}; auto s = accumulate(lst.begin(),lst.end(),0.0); // calculate the sum cout << s << '\n'; // print 10014.9999 } These algorithms work for every standard-library sequence and can have operations supplied as arguments (§40.6).
ptg10564057 Section 5.6 .2 Complex Numbers 129 5.6.2 Complex Numbers The standard library supports a family of complex number types along the lines of the complex class described in §2.3 . To support complex numbers where the scalars are single-precision float- ing-point numbers (floats), double-precision floating-point numbers (doubles), etc., the standard library complex is a template: template<typename Scalar> class complex { public: complex(const Scalar& re ={}, const Scalar& im ={}); // ... }; The usual arithmetic operations and the most common mathematical functions are supported for complex numbers. For example: void f(complex<float> fl, complex<double> db) { complex<long double> ld {fl+sqrt(db)}; db += fl∗3; fl = pow(1/fl,2); // ... } The sqrt() and pow() (exponentiation) functions are among the usual mathematical functions defined in <complex>. For more details, see §40.4 . 5.6.3 Random Numbers Random numbers are useful in many contexts, such as testing, games, simulation, and security. The diversity of application areas is reflected in the wide selection of random number generators provided by the standard library in <random>. A random number generator consists of two parts: [1] an engine that produces a sequence of random or pseudo-random values. [2] a distribution that maps those values into a mathematical distribution in a range. Examples of distributions are uniform_int_distribution (where all integers produced are equally likely), normal_distribution (‘‘the bell curve’’), and exponential_distribution (exponential growth); each for some specified range. For example: using my_engine = default_random_engine; // type of engine using my_distribution = uniform_int_distribution<>; // type of distribution my_engine re {}; // the default engine my_distribution one_to_six {1,6}; // distribution that maps to the ints 1..6 auto die = bind(one_to_six,re); // make a generator int x = die(); // roll the die: x becomes a value in [1:6] The standard-library function bind() makes a function object that will invoke its first argument (here, one_to_six) given its second argument (here, re) as its argument (§33.5 .1). Thus a call die() is equivalent to a call one_to_six(re).
ptg10564057 130 A Tour of C++: Concurrency and Utilities Chapter 5 Thanks to its uncompromising attention to generality and performance one expert has deemed the standard-library random number component ‘‘what every random number library wants to be when it grows up.’’ However, it can hardly be deemed ‘‘novice friendly.’’ The using statements makes what is being done a bit more obvious. Instead, I could just have written: auto die = bind(uniform_int_distribution<>{1,6}, default_random_engine{}); Which version is the more readable depends entirely on the context and the reader. For novices (of any background) the fully general interface to the random number library can be a serious obstacle. A simple uniform random number generator is often sufficient to get started. For example: Rand_int rnd {1,10}; // make a random number generator for [1:10] int x = rnd(); // x is a number in [1:10] So, how could we get that? We have to get something like die() inside a class Rand_int: class Rand_int { public: Rand_int(int low, int high) :dist{low,high} { } int operator()() { return dist(re); } // draw an int private: default_random_engine re; uniform_int_distribution<> dist; }; That definition is still ‘‘expert level,’’ but the use of Rand_int() is manageable in the first week of a C++ course for novices. For example: int main() { Rand_int rnd {0,4}; // make a uniform random number generator vector<int> histogram(5); // make a vector of size 5 for (int i=0; i!=200; ++i) ++histogram[rnd()]; // fill histogram with the frequencies of numbers [0:4] for (int i = 0; i!=mn.size(); ++i) { // write out a bar graph cout << i << '\t'; for (int j=0; j!=mn[i]; ++j) cout << '∗'; cout << endl; } } The output is a (reassuringly boring) uniform distribution (with reasonable statistical variation): 0 ∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗ 1 ∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗ 2 ∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗ 3 ∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗ 4 ∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗
ptg10564057 Section 5.6 .3 Random Numbers 131 There is no standard graphics library for C++, so I use ‘‘ASCII graphics.’’ Obviously, there are lots of open source and commercial graphics and GUI libraries for C++, but in this book I’ll restrict myself to ISO standard facilities. For more information about random numbers, see §40.7 . 5.6.4 Vector Arithmetic The vector described in §4.4 .1 was designed to be a general mechanism for holding values, to be flexible, and to fit into the architecture of containers, iterators, and algorithms. However, it does not support mathematical vector operations. Adding such operations to vector would be easy, but its generality and flexibility precludes optimizations that are often considered essential for serious numerical work. Consequently, the standard library provides (in <valarray>)avector-like template, called valarray, that is less general and more amenable to optimization for numerical computation: template<typename T> class valarray { // ... }; The usual arithmetic operations and the most common mathematical functions are supported for valarrays. For example: void f(valarray<double>& a1, valarray<double>& a2) { valarray<double> a = a1∗3.14+a2/a1; // numeric array operators *, +, /, and = a2 += a1∗3.14; a = abs(a); double d = a2[7]; // ... } For more details, see §40.5 . In particular, valarray offers stride access to help implement multidi- mensional computations. 5.6.5 Numeric Limits In <limits>, the standard library provides classes that describe the properties of built-in types – such as the maximum exponent of a float or the number of bytes in an int; see §40.2 . For example, we can assert that a char is signed: static_assert(numeric_limits<char>::is_signed,"unsigned characters!"); static_assert(100000<numeric_limits<int>::max(),"small ints!"); Note that the second assert (only) works because numeric_limits<int>::max() is a constexpr function (§2.2 .3, §10.4).
ptg10564057 132 A Tour of C++: Concurrency and Utilities Chapter 5 5.7 Advice [1] Use resource handles to manage resources (RAII); §5.2 . [2] Use unique_ptr to refer to objects of polymorphic type; §5.2 .1. [3] Use shared_ptr to refer to shared objects; §5.2 .1 . [4] Use type-safe mechanisms for concurrency; §5.3 . [5] Minimize the use of shared data; §5.3.4 . [6] Don’t choose shared data for communication because of ‘‘efficiency’’ without thought and preferably not without measurement; §5.3 .4. [7] Think in terms of concurrent tasks, rather than threads; §5.3 .5 . [8] A library doesn’t have to be large or complicated to be useful; §5.4 . [9] Time your programs before making claims about efficiency; §5.4.1 . [10] You can write code to explicitly depend on properties of types; §5.4 .2 . [11] Use regular expressions for simple pattern matching; §5.5 . [12] Don’t try to do serious numeric computation using only the language; use libraries; §5.6. [13] Properties of numeric types are accessible through numeric_limits; §5.6 .5 .
ptg10564057 Part II Basic Facilities This part describes C++’s built-in types and the basic facilities for constructing pro- grams out of them. The C subset of C++ is presented together with C++’s additional support for traditional styles of programming. It also discusses the basic facilities for composing a C++ program out of logical and physical parts. Chapters 6 Types and Declarations 7 Pointers, Arrays, and References 8 Structures, Unions, and Enumerations 9 Statements 10 Expressions 11 Select Operations 12 Functions 13 Exception Handling 14 Namespaces 15 Source Files and Programs
ptg10564057 134 Basic Facilities Part II ‘‘... I have long entertained a suspicion, with regard to the decisions of philosophers upon all subjects, and found in myself a greater inclination to dispute, than assent to their conclusions. There is one mistake, to which they seem liable, almost without exception; they confine too much their principles, and make no account of that vast variety, which nature has so much affected in all her operations. When a philosopher has once laid hold of a favourite principle, which perhaps accounts for many natural effects, he extends the same principle over the whole creation, and reduces to it every phænomenon, though by the most violent and absurd reasoning. ...’’ – David Hume, Essays, Moral, Political, and Literary. PART I. (1752)
ptg10564057 6 Types and Declarations Perfection is achieved only on the point of collapse. – C. N . Parkinson • The ISO C++ Standard Implementations; The Basic Source Character Set • Types Fundamental Types; Booleans; Character Types; Integer Types; Floating-Point Types; Pre- fixes and Suffixes; void; Sizes; Alignment • Declarations The Structure of Declarations; Declaring Multiple Names; Names; Scope; Initialization; Deducing a Type: auto and decltype() • Objects and Values Lvalues and Rvalues; Lifetimes of Objects • Type Aliases • Advice 6.1 The ISO C++ Standard The C++ language and standard library are defined by their ISO standard: ISO/IEC 14882:2011. In this book, references to the standard are of the form §iso.23.3 .6 .1 . In cases where the text of this book is considered imprecise, incomplete, or possibly wrong, consult the standard. But don’t expect the standard to be a tutorial or to be easily accessible by non-experts. Strictly adhering to the C++ language and library standard doesn’t by itself guarantee good code or even portable code. The standard doesn’t say whether a piece of code is good or bad; it simply says what a programmer can and cannot rely on from an implementation. It is easy to write perfectly awful standard-conforming programs, and most real-world programs rely on features that the standard does not guarantee to be portable. They do so to access system interfaces and
ptg10564057 136 Types and Declarations Chapter 6 hardware features that cannot be expressed directly in C++ or require reliance on specific imple- mentation details. Many important things are deemed implementation-defined by the standard. This means that each implementation must provide a specific, well-defined behavior for a construct and that behav- ior must be documented. For example: unsigned char c1 = 64; // well defined: a char has at least 8 bits and can always hold 64 unsigned char c2 = 1256; // implementation-defined: truncation if a char has only 8 bits The initialization of c1 is well defined because a char must be at least 8 bits. However, the behavior of the initialization of c2 is implementation-defined because the number of bits in a char is imple- mentation-defined. If the char has only 8 bits, the value 1256 will be truncated to 232 (§10.5 .2 .1). Most implementation-defined features relate to differences in the hardware used to run a program. Other behaviors are unspecified; that is, a range of possible behaviors are acceptable, but the implementer is not obliged to specify which actually occur. Usually, the reason for deeming some- thing unspecified is that the exact behavior is unpredictable for fundamental reasons. For example, the exact value returned by new is unspecified. So is the value of a variable assigned to from two threads unless some synchronization mechanism has been employed to prevent a data race (§41.2). When writing real-world programs, it is usually necessary to rely on implementation-defined behavior. Such behavior is the price we pay for the ability to operate effectively on a large range of systems. For example, C++ would have been much simpler if all characters had been 8 bits and all pointers 32 bits. However, 16-bit and 32-bit character sets are not uncommon, and machines with 16-bit and 64-bit pointers are in wide use. To maximize portability, it is wise to be explicit about what implementation-defined features we rely on and to isolate the more subtle examples in clearly marked sections of a program. A typical example of this practice is to present all dependencies on hardware sizes in the form of constants and type definitions in some header file. To support such techniques, the standard library provides numeric_limits (§40.2). Many assumptions about implementation-defined features can be checked by stating them as static assertions (§2.4 .3.3). For example: static_assert(4<=sizeof(int),"sizeof(int) too small"); Undefined behavior is nastier. A construct is deemed undefined by the standard if no reasonable behavior is required by an implementation. Typically, some obvious implementation technique will cause a program using an undefined feature to behave very badly. For example: const int size = 4∗1024; char page[size]; void f() { page[size+size] = 7; // undefined } Plausible outcomes of this code fragment include overwriting unrelated data and triggering a hard- ware error/exception. An implementation is not required to choose among plausible outcomes. Where powerful optimizers are used, the actual effects of undefined behavior can become quite unpredictable. If a set of plausible and easily implementable alternatives exist, a feature is deemed
ptg10564057 Section 6.1 The ISO C++ Standard 137 unspecified or implementation-defined rather than undefined. It is worth spending considerable time and effort to ensure that a program does not use some- thing deemed unspecified or undefined by the standard. In many cases, tools exist to help do this. 6.1.1 Implementations A C++ implementation can be either hosted or freestanding (§iso.17.6.1 .3). A hosted implementa- tion includes all the standard-library facilities as described in the standard (§30.2) and in this book. A freestanding implementation may provide fewer standard-library facilities, as long as the follow- ing are provided: Freestanding Implementation Headers Types <cstddef> §10.3 .1 Implementation properties <cfloat> <limits> <climits> §40.2 Integer types <cstdint> §43.7 Start and termination <cstdlib> §43.7 Dynamic memory management <new> §11.2 .3 Type identification <typeinfo> §22.5 Exception handling <exception> §30.4 .1 .1 Initializer lists <initializer_list> §30.3 .1 Other run-time support <cstdalign> <cstdarg> <cstdbool> §12.2 .4, §44.3 .4 Type traits <type_traits> §35.4 .1 Atomics <atomic> §41.3 Freestanding implementations are meant for code running with only the most minimal operating system support. Many implementations also provide a (non-standard) option for not using excep- tions for really minimal, close-to-the-hardware, programs. 6.1.2 The Basic Source Character Set The C++ standard and the examples in this book are written using the basic source character set consisting of the letters, digits, graphical characters, and whitespace characters from the U.S. vari- ant of the international 7-bit character set ISO 646-1983 called ASCII (ANSI3.4 -1968). This can cause problems for people who use C++ in an environment with a different character set: • ASCII contains punctuation characters and operator symbols (such as ], {, and !) that are not available in some character sets. • We need a notation for characters that do not have a convenient character representation (such as newline and ‘‘the character with value 17’’). • ASCII doesn’t contain characters (such as ñ, Þ, and Æ) that are used for writing languages other than English. To use an extended character set for source code, a programming environment can map the extended character set into the basic source character set in one of several ways, for example, by using universal character names (§6.2 .3 .2).
ptg10564057 138 Types and Declarations Chapter 6 6.2 Types Consider: x = y+f(2); For this to make sense in a C++ program, the names x, y, and f must be suitably declared. That is, the programmer must specify that entities named x, y, and f exist and that they are of types for which = (assignment), + (addition), and () (function call), respectively, are meaningful. Every name (identifier) in a C++ program has a type associated with it. This type determines what operations can be applied to the name (that is, to the entity referred to by the name) and how such operations are interpreted. For example: float x; // x is a floating-point variable inty=7; // y is an integer variable with the initial value 7 float f(int); // f is a function taking an argument of type int and returning a floating-point number These declarations would make the example meaningful. Because y is declared to be an int,itcan be assigned to, used as an operand for +, etc. On the other hand, f is declared to be a function that takes an int as its argument, so it can be called given the interger 2. This chapter presents fundamental types (§6.2 .1) and declarations (§6.3). Its examples just demonstrate language features; they are not intended to do anything useful. More extensive and realistic examples are saved for later chapters. This chapter simply provides the most basic ele- ments from which C++ programs are constructed. You must know these elements, plus the termi- nology and simple syntax that go with them, in order to complete a real project in C++ and espe- cially to read code written by others. However, a thorough understanding of every detail mentioned in this chapter is not a requirement for understanding the following chapters. Consequently, you may prefer to skim through this chapter, observing the major concepts, and return later as the need for understanding more details arises. 6.2.1 Fundamental Types C++ has a set of fundamental types corresponding to the most common basic storage units of a computer and the most common ways of using them to hold data: §6.2 .2 A Boolean type (bool) §6.2 .3 Character types (such as char and wchar_t) §6.2 .4 Integer types (such as int and long long) §6.2 .5 Floating-point types (such as double and long double) §6.2 .7 A type, void, used to signify the absence of information From these types, we can construct other types using declarator operators: §7.2 Pointer types (such as int∗) §7.3 Array types (such as char[]) §7.7 Reference types (such as double& and vector<int>&&) In addition, a user can define additional types: §8.2 Data structures and classes (Chapter 16) §8.4 Enumeration types for representing specific sets of values (enum and enum class)
ptg10564057 Section 6.2 .1 Fundamental Types 139 The Boolean, character, and integer types are collectively called integral types. The integral and floating-point types are collectively called arithmetic types. Enumerations and classes (Chapter 16) are called user-defined types because they must be defined by users rather than being available for use without previous declaration, the way fundamental types are. In contrast, fundamental types, pointers, and references are collectively referred to as built-in types. The standard library provides many user-defined types (Chapter 4, Chapter 5). The integral and floating-point types are provided in a variety of sizes to give the programmer a choice of the amount of storage consumed, the precision, and the range available for computations (§6.2 .8). The assumption is that a computer provides bytes for holding characters, words for hold- ing and computing integer values, some entity most suitable for floating-point computation, and addresses for referring to those entities. The C++ fundamental types together with pointers and arrays present these machine-level notions to the programmer in a reasonably implementation-inde- pendent manner. For most applications, we could use bool for logical values, char for characters, int for integer values, and double for floating-point values. The remaining fundamental types are variations for optimizations, special needs, and compatibility that are best ignored until such needs arise. 6.2.2 Booleans A Boolean, bool, can have one of the two values true or false. A Boolean is used to express the results of logical operations. For example: void f(int a, int b) { bool b1 {a==b}; // ... } If a and b have the same value, b1 becomes true; otherwise, b1 becomes false. A common use of bool is as the type of the result of a function that tests some condition (a pred- icate). For example: bool is_open(File∗); bool greater(int a, int b) { return a>b; } By definition, true has the value 1 when converted to an integer and false has the value 0. Con- versely, integers can be implicitly converted to bool values: nonzero integers convert to true and 0 converts to false. For example: bool b1 = 7; // 7!=0, so b becomes true bool b2 {7}; // error: narrowing (§2.2 .2, §10.5) int i1 = true; // i1 becomes 1 int i2 {true}; // i2 becomes 1 If you prefer to use the {}-initializer syntax to prevent narrowing, yet still want to convert an int to a bool, you can be explicit:
ptg10564057 140 Types and Declarations Chapter 6 void f(int i) { bool b {i!=0}; // ... }; In arithmetic and logical expressions, bools are converted to ints; integer arithmetic and logical operations are performed on the converted values. If the result needs to be converted back to bool, a 0 is converted to false and a nonzero value is converted to true. For example: bool a = true; bool b = true; boolx=a+b; //a+bis2,soxbecomestrue bool y = a||b; // a||b is 1, so y becomes true ("||" means "or") bool z = a−b; // a-b is 0, so z becomes false A pointer can be implicitly converted to a bool (§10.5 .2 .5). A non-null pointer converts to true; pointers with the value nullptr convert to false. For example: void g(int∗ p) { boolb=p; // narrows to true or false bool b2 {p!=nullptr}; // explicit test against nullptr if (p) { // equivalent to p!=nullptr // ... } } I prefer if (p) over if (p!=nullptr) because it more directly expresses the notion ‘‘if p is valid’’ and also because it is shorter. The shorter form leaves fewer opportunities for mistakes. 6.2.3 Character Types There are many character sets and character set encodings in use. C++ provides a variety of char- acter types that reflect that – often bewildering – variety: • char: The default character type, used for program text. A char is used for the implementa- tion’s character set and is usually 8 bits. • signed char: Like char, but guaranteed to be signed, that is, capable of holding both positive and negative values. • unsigned char: Like char, but guaranteed to be unsigned. • wchar_t: Provided to hold characters of a larger character set such as Unicode (see §7.3 .2 .2). The size of wchar_t is implementation-defined and large enough to hold the largest character set supported by the implementation’s locale (Chapter 39). • char16_t: A type for holding 16-bit character sets, such as UTF-16. • char32_t: A type for holding 32-bit character sets, such as UTF-32. These are six distinct types (despite the fact that the _t suffix is often used to denote aliases; §6.5). On each implementation, the char type will be identical to that of either signed char or unsigned
ptg10564057 Section 6.2 .3 Character Types 141 char, but these three names are still considered separate types. A char variable can hold a character of the implementation’s character set. For example: char ch = 'a'; Almost universally, a char has 8 bits so that it can hold one of 256 different values. Typically, the character set is a variant of ISO-646, for example ASCII, thus providing the characters appearing on your keyboard. Many problems arise from the fact that this set of characters is only partially standardized. Serious variations occur between character sets supporting different natural languages and between character sets supporting the same natural language in different ways. Here, we are inter- ested only in how such differences affect the rules of C++. The larger and more interesting issue of how to program in a multilingual, multi-character-set environment is beyond the scope of this book, although it is alluded to in several places (§6.2 .3, §36.2 .1, Chapter 39). It is safe to assume that the implementation character set includes the decimal digits, the 26 alphabetic characters of English, and some of the basic punctuation characters. It is not safe to assume that: • There are no more than 127 characters in an 8-bit character set (e.g ., some sets provide 255 characters). • There are no more alphabetic characters than English provides (most European languages provide more, e.g ., æ, þ, and ß). • The alphabetic characters are contiguous (EBCDIC leaves a gap between 'i' and 'j'). • Every character used to write C++ is available (e.g ., some national character sets do not pro- vide{,},[,],|,and\). •A char fits in 1 byte. There are embedded processors without byte accessing hardware for which a char is 4 bytes. Also, one could reasonably use a 16-bit Unicode encoding for the basic chars. Whenever possible, we should avoid making assumptions about the representation of objects. This general rule applies even to characters. Each character has an integer value in the character set used by the implementation. For exam- ple, the value of 'b' is 98 in the ASCII character set. Here is a loop that outputs the the integer value of any character you care to input: void intval() { for(charc;cin>>c;) cout<<"thevalueof'"<<c<<"'is"<<int{c}<<'\n'; } The notation int{c} gives the integer value for a character c (‘‘the int we can construct from c’’). The possibility of converting a char to an integer raises the question: is a char signed or unsigned? The 256 values represented by an 8-bit byte can be interpreted as the values 0 to 255 or as the val- ues −127 to 127. No, not −128 to 127 as one might expect: the C++ standard leaves open the possi- bility of one’s-complement hardware and that eliminates one value; thus, a use of −128 is non- portable. Unfortunately, the choice of signed or unsigned for a plain char is implementation- defined. C++ provides two types for which the answer is definite: signed char, which can hold at least the values −127 to 127, and unsigned char, which can hold at least the values 0 to 255.
ptg10564057 142 Types and Declarations Chapter 6 Fortunately, the difference matters only for values outside the 0 to 127 range, and the most common characters are within that range. Values outside that range stored in a plain char can lead to subtle portability problems. See §6.2 .3 .1 if you need to use more than one type of char or if you store integers in char variables. Note that the character types are integral types (§6.2 .1) so that arithmetic and bitwise logical operations (§10.3) apply. For example: void digits() { for (int i=0; i!=10; ++i) cout << static_cast<char>('0'+i); } This is a way of writing the ten digits to cout. The character literal '0' is converted to its integer value and i is added. The resulting int is then converted to a char and written to cout. Plain '0'+i is an int, so if I had left out the static_cast<char>, the output would have been something like 48, 49, and so on, rather than 0, 1, and so on. 6.2 .3.1 Signed and Unsigned Characters It is implementation-defined whether a plain char is considered signed or unsigned. This opens the possibility for some nasty surprises and implementation dependencies. For example: char c = 255; // 255 is ‘‘all ones,’’ hexadecimal 0xFF inti=c; What will be the value of i? Unfortunately, the answer is undefined. On an implementation with 8-bit bytes, the answer depends on the meaning of the ‘‘all ones’’ char bit pattern when extended into an int. On a machine where a char is unsigned, the answer is 255. On a machine where a char is signed, the answer is −1 . In this case, the compiler might warn about the conversion of the literal 255 to the char value −1. However, C++ does not offer a general mechanism for detecting this kind of problem. One solution is to avoid plain char and use the specific char types only. Unfortunately, some standard-library functions, such as strcmp(), take plain chars only (§43.4). A char must behave identically to either a signed char or an unsigned char. However, the three char types are distinct, so you can’t mix pointers to different char types. For example: void f(char c, signed char sc, unsigned char uc) { char∗ pc = &uc; // error: no pointer conversion signed char∗ psc = pc; // error: no pointer conversion unsigned char∗ puc = pc; // error: no pointer conversion psc = puc; // error: no pointer conversion } Variables of the three char types can be freely assigned to each other. However, assigning a too- large value to a signed char (§10.5.2 .1) is still undefined. For example: void g(char c, signed char sc, unsigned char uc) { c = 255; // implementation-defined if plain chars are signed and have 8 bits
ptg10564057 Section 6.2 .3 .1 Signed and Unsigned Characters 143 c=sc; //OK c = uc; // implementation-defined if plain chars are signed and if uc’s value is too large sc = uc; // implementation defined if uc’s value is too large uc = sc; // OK: conversion to unsigned sc = c; // implementation-defined if plain chars are unsigned and if c’s value is too large uc = c; // OK: conversion to unsigned } To be concrete, assume that a char is 8 bits: signed char sc = −160; unsigned char uc = sc; // uc == 116 (because 256-160==116) cout << uc; // print 't' char count[256]; // assume 8-bit chars ++count[sc]; // likely disaster: out-of-range access ++count[uc]; // OK None of these potential problems and confusions occur if you use plain char throughout and avoid negative character values. 6.2 .3.2 Character Literals A character literal is a single character enclosed in single quotes, for example, 'a' and '0'. The type of a character literal is char. A character literal can be implicitly converted to its integer value in the character set of the machine on which the C++ program is to run. For example, if you are run- ning on a machine using the ASCII character set, the value of '0' is 48. The use of character literals rather than decimal notation makes programs more portable. A few characters have standard names that use the backslash, \,as an escape character: Name ASCII Name C++ Name Newline NL (LF) \n Horizontal tab HT \t Vertical tab VT \v Backspace BS \b Carriage return CR \r Form feed FF \f Alert BEL \a Backslash \ \\ Question mark ? \? Single quote ’ \’ Double quote " \" Octal number ooo \ooo Hexadecimal number hhh \xhhh ... Despite their appearance, these are single characters. We can represent a character from the implementation character set as a one-, two-, or three- digit octal number (\ followed by octal digits) or as a hexadecimal number (\x followed by
ptg10564057 144 Types and Declarations Chapter 6 hexadecimal digits). There is no limit to the number of hexadecimal digits in the sequence. A sequence of octal or hexadecimal digits is terminated by the first character that is not an octal digit or a hexadecimal digit, respectively. For example: Octal Hexadecimal Decimal ASCII '\6' '\x6' 6 ACK '\60' '\x30' 48 '0' '\137' '\x05f' 95 '_' This makes it possible to represent every character in the machine’s character set and, in particular, to embed such characters in character strings (see §7.3 .2). Using any numeric notation for charac- ters makes a program nonportable across machines with different character sets. It is possible to enclose more than one character in a character literal, for example, 'ab'. Such uses are archaic, implementation-dependent, and best avoided. The type of such a multicharacter literal is int. When embedding a numeric constant in a string using the octal notation, it is wise always to use three digits for the number. The notation is hard enough to read without having to worry about whether or not the character after a constant is a digit. For hexadecimal constants, use two digits. Consider these examples: char v1[] = "a\xah\129"; // 6 chars: 'a' '\xa' 'h' '\12' '9' '\0' char v2[] = "a\xah\127"; // 5 chars: 'a' '\xa' 'h' '\127' '\0' char v3[] = "a\xad\127"; // 4 chars: 'a' '\xad' '\127' '\0' char v4[] = "a\xad\0127"; // 5 chars: 'a' '\xad' '\012' '7' '\0' Wide character literals are of the form L'ab' and are of type wchar_t. The number of characters between the quotes and their meanings are implementation-defined. A C++ program can manipulate character sets that are much richer than the 127-character ASCII set, such as Unicode. Literals of such larger character sets are presented as sequences of four or eight hexadecimal digits preceded by a U or a u. For example: U'\UFADEBEEF' u'\uDEAD' u'\xDEAD' The shorter notation u'\uXXXX' is equivalent to U'\U0000XXXX' for any hexadecimal digit X. A num- ber of hexadecimal digits different from four or eight is a lexical error. The meaning of the hexa- decimal number is defined by the ISO/IEC 10646 standard and such values are called universal character names. In the C++ standard, universal character names are described in §iso.2 .2, §iso.2 .3, §iso.2 .14.3, §iso.2 .14 .5, and §iso.E. 6.2.4 Integer Types Like char, each integer type comes in three forms: ‘‘plain’’ int, signed int, and unsigned int. In addi- tion, integers come in four sizes: short int, ‘‘plain’’ int, long int, and long long int.Along int can be referred to as plain long, and a long long int can be referred to as plain long long. Similarly, short is a synonym for short int, unsigned for unsigned int, and signed for signed int. No, there is no long short int equivalent to int.
ptg10564057 Section 6.2 .4 Integer Types 145 The unsigned integer types are ideal for uses that treat storage as a bit array. Using an unsigned instead of an int to gain one more bit to represent positive integers is almost never a good idea. Attempts to ensure that some values are positive by declaring variables unsigned will typically be defeated by the implicit conversion rules (§10.5 .1, §10.5 .2 .1). Unlike plain chars, plain ints are always signed. The signed int types are simply more explicit synonyms for their plain int counterparts, rather than different types. If you need more detailed control over integer sizes, you can use aliases from <cstdint> (§43.7), such as int64_t (a signed integer with exactly 64 bits), uint_fast16_t (an unsigned integer with exactly 8 bits, supposedly the fastest such integer), and int_least32_t (a signed integer with at least 32 bits, just like plain int). The plain integer types have well-defined minimal sizes (§6.2 .8), so the <cstdint> are sometimes redundant and can be overused. In addition to the standard integer types, an implementation may provide extended integer types (signed and unsigned). These types must behave like integers and are considered integer types when considering conversions and integer literal values, but they usually have greater range (occupy more space). 6.2 .4.1 Integer Literals Integer literals come in three guises: decimal, octal, and hexadecimal. Decimal literals are the most commonly used and look as you would expect them to: 7 1234 976 12345678901234567890 The compiler ought to warn about literals that are too long to represent, but an error is only guaran- teed for {} initializers (§6.3 .5). A literal starting with zero followed by x or X (0x or 0X) is a hexadecimal (base 16) number. A literal starting with zero but not followed by x or X is an octal (base 8) number. For example: Decimal Octal Hexadecimal 0 0x0 2 02 0x2 63 077 0x3f 83 0123 0x63 The letters a, b, c, d, e, and f, or their uppercase equivalents, are used to represent 10, 11, 12, 13, 14, and 15, respectively. Octal and hexadecimal notations are most useful for expressing bit patterns. Using these notations to express genuine numbers can lead to surprises. For example, on a machine on which an int is represented as a two’s complement 16-bit integer, 0xffff is the negative decimal number −1 . Had more bits been used to represent an integer, it would have been the positive deci- mal number 65535. The suffix U can be used to write explicitly unsigned literals. Similarly, the suffix L can be used to write explicitly long literals. For example, 3 is an int, 3U is an unsigned int, and 3L is a long int. Combinations of suffixes are allowed. For example: cout << 0xF0UL << ' ' << 0LU << '\n';
ptg10564057 146 Types and Declarations Chapter 6 If no suffix is provided, the compiler gives an integer literal a suitable type based on its value and the implementation’s integer sizes (§6.2 .4 .2). It is a good idea to limit the use of nonobvious constants to a few well-commented const (§7.5), constexpr (§10.4), and enumerator (§8.4) initializers. 6.2 .4.2 Types of Integer Literals In general, the type of an integer literal depends on its form, value, and suffix: • If it is decimal and has no suffix, it has the first of these types in which its value can be rep- resented: int, long int, long long int. • If it is octal or hexadecimal and has no suffix, it has the first of these types in which its value can be represented: int, unsigned int, long int, unsigned long int, long long int, unsigned long long int. • If it is suffixed by u or U, its type is the first of these types in which its value can be repre- sented: unsigned int, unsigned long int, unsigned long long int. • If it is decimal and suffixed by l or L, its type is the first of these types in which its value can be represented: long int, long long int. • If it is octal or hexadecimal and suffixed by l or L, its type is the first of these types in which its value can be represented: long int, unsigned long int, long long int, unsigned long long int. • If it is suffixed by ul, lu, uL, Lu, Ul, lU, UL,orLU, its type is the first of these types in which its value can be represented: unsigned long int, unsigned long long int. • If it is decimal and is suffixed by ll or LL, its type is long long int. • If it is octal or hexadecimal and is suffixed by ll or LL, its type is the first of these types in which its value can be represented: long long int, unsigned long long int. • If it is suffixed by llu, llU, ull, Ull, LLu, LLU, uLL,orULL, its type is unsigned long long int. For example, 100000 is of type int on a machine with 32-bit ints but of type long int on a machine with 16-bit ints and 32-bit longs. Similarly, 0XA000 is of type int on a machine with 32-bit intsbut of type unsigned int on a machine with 16-bit ints. These implementation dependencies can be avoided by using suffixes: 100000L is of type long int on all machines and 0XA000U is of type unsigned int on all machines. 6.2.5 Floating-Point Types The floating-point types represent floating-point numbers. A floating-point number is an approxi- mation of a real number represented in a fixed amount of memory. There are three floating-point types: float (single-precision), double (double-precision), and long double (extended-precision). The exact meaning of single-, double-, and extended-precision is implementation-defined. Choosing the right precision for a problem where the choice matters requires significant under- standing of floating-point computation. If you don’t have that understanding, get advice, take the time to learn, or use double and hope for the best. 6.2 .5.1 Floating-Point Literals By default, a floating-point literal is of type double. Again, a compiler ought to warn about float- ing-point literals that are too large to be represented. Here are some floating-point literals:
ptg10564057 Section 6.2 .5 .1 Floating-Point Literals 147 1.23 .23 0.23 1. 1.0 1.2e10 1.23e−15 Note that a space cannot occur in the middle of a floating-point literal. For example, 65.43 e−21 is not a floating-point literal but rather four separate lexical tokens (causing a syntax error): 65.43e−21 If you want a floating-point literal of type float, you can define one using the suffix f or F: 3.14159265f 2.0f 2.997925F 2.9e−3f If you want a floating-point literal of type long double, you can define one using the suffix l or L: 3.14159265L 2.0L 2.997925L 2.9e−3L 6.2.6 Prefixes and Suffixes There is a minor zoo of suffixes indicating types of literals and also a few prefixes: Arithmetic Literal Prefixes and Suffixes Notation ∗fix Meaning Example Reference ISO 0 prefix octal 0776 §6.2.4 .1 §iso.2 .14 .2 0x 0X prefix hexadecimal 0xff §6.2.4 .1 §iso.2 .14 .2 uU suffix unsigned 10U §6.2.4 .1 §iso.2 .14 .2 lL suffix long 20000L §6.2.4 .1 §iso.2 .14 .2 ll LL suffix long long 20000LL §6.2.4 .1 §iso.2 .14 .2 fF suffix float 10f §6.2.5 .1 §iso.2 .14 .4 eE infix floating-point 10e−4 §6.2.5 .1 §iso.2 .14 .4 . infix floating-point 12.3 §6.2.5 .1 §iso.2 .14 .4 ' prefix char 'c' §6.2.3 .2 §iso.2 .14 .3 u' prefix char16_t u'c' §6.2.3 .2 §iso.2 .14 .3 U' prefix char32_t U'c' §6.2.3 .2 §iso.2 .14 .3 L' prefix wchar_t L'c' §6.2.3 .2 §iso.2 .14 .3 " prefix string "mess" §7.3.2 §iso.2 .14 .5 R" prefix raw string R"(\b)" §7.3.2 .1 §iso.2 .14 .5 u8" u8R" prefix UTF-8 string u8"foo" §7.3.2 .2 §iso.2 .14 .5 u" uR" prefix UTF-16 string u"foo" §7.3.2 .2 §iso.2 .14 .5 U" UR" prefix UTF-32 string U"foo" §7.3.2 .2 §iso.2 .14 .5 L" LR" prefix wchar_t string L"foo" §7.3.2 .2 §iso.2 .14 .5 Note that ‘‘string’’ here means ‘‘string literal’’ (§7.3 .2) rather than ‘‘of type std::string.’’ Obviously, we could also consider . and e as infix and R" and u8" as the first part of a set of delimiters. However, I consider the nomenclature less important than giving an overview of the bewildering variety of literals. The suffixes l and L can be combined with the suffixes u and U to express unsigned long types. For example:
ptg10564057 148 Types and Declarations Chapter 6 1LU // unsigned long 2UL // unsigned long 3ULL // unsigned long long 4LLU // unsigned long long 5LUL // error The suffixes l and L can be used for floating-point literals to express long double. For example: 1L // long int 1.0L // long double Combinations of R, L, and u prefixes are allowed, for example, uR"∗∗(foo\(bar))∗∗". Note the dra- matic difference in the meaning of a U prefix for a character (unsigned) and for a string UTF-32 encoding (§7.3 .2 .2). In addition, a user can define new suffixes for user-defined types. For example, by defining a user-defined literal operator (§19.2 .6), we can get "foo bar"s // a literal of type std::string 123_km // a literal of type Distance Suffixes not starting with _ are reserved for the standard library. 6.2.7 void The type void is syntactically a fundamental type. It can, however, be used only as part of a more complicated type; there are no objects of type void. It is used either to specify that a function does not return a value or as the base type for pointers to objects of unknown type. For example: void x; // error: there are no void objects void& r; // error: there are no references to void void f(); // function f does not return a value (§12.1 .4) void∗ pv; // pointer to object of unknown type (§7.2 .1) When declaring a function, you must specify the type of the value returned. Logically, you would expect to be able to indicate that a function didn’t return a value by omitting the return type. How- ever, that would make a mess of the grammar (§iso.A). Consequently, void is used as a ‘‘pseudo return type’’ to indicate that a function doesn’t return a value. 6.2.8 Sizes Some of the aspects of C++’s fundamental types, such as the size of an int, are implementation- defined (§6.1). I point out these dependencies and often recommend avoiding them or taking steps to minimize their impact. Why should you bother? People who program on a variety of systems or use a variety of compilers care a lot because if they don’t, they are forced to waste time finding and fixing obscure bugs. People who claim they don’t care about portability usually do so because they use only a single system and feel they can afford the attitude that ‘‘the language is what my com- piler implements.’’ This is a narrow and shortsighted view. If your program is a success, it will be ported, so someone will have to find and fix problems related to implementation-dependent fea- tures. In addition, programs often need to be compiled with other compilers for the same system, and even a future release of your favorite compiler may do some things differently from the current
ptg10564057 Section 6.2 .8 Sizes 149 one. It is far easier to know and limit the impact of implementation dependencies when a program is written than to try to untangle the mess afterward. It is relatively easy to limit the impact of implementation-dependent language features. Limit- ing the impact of system-dependent library facilities is far harder. Using standard-library facilities wherever feasible is one approach. The reason for providing more than one integer type, more than one unsigned type, and more than one floating-point type is to allow the programmer to take advantage of hardware characteris- tics. On many machines, there are significant differences in memory requirements, memory access times, and computation speed among the different varieties of fundamental types. If you know a machine, it is usually easy to choose, for example, the appropriate integer type for a particular vari- able. Writing truly portable low-level code is harder. Here is a graphical representation of a plausible set of fundamental types and a sample string literal (§7.3 .2): 'a' 1 756 100000000 1234567890 char bool short int long 1234567890 &c1 1234567e34 1234567e34 Hello, world!\0 long long int∗ double long double char[14] On the same scale (.2 inch to a byte), a megabyte of memory would stretch about 3 miles (5 km) to the right. Sizes of C++ objects are expressed in terms of multiples of the size of a char, so by definition the size of a char is 1. The size of an object or type can be obtained using the sizeof operator (§10.3). This is what is guaranteed about sizes of fundamental types: • 1 ≡ sizeof(char) ≤ sizeof(short) ≤ sizeof(int) ≤ sizeof(long) ≤ sizeof(long long) • 1 ≤ sizeof(bool) ≤ sizeof(long) • sizeof(char) ≤ sizeof(wchar_t) ≤ sizeof(long) • sizeof(float) ≤ sizeof(double) ≤ sizeof(long double) • sizeof(N) ≡ sizeof(signed N) ≡ sizeof(unsigned N)
ptg10564057 150 Types and Declarations Chapter 6 In that last line, N can be char, short, int, long,orlong long. In addition, it is guaranteed that a char has at least 8 bits, a short at least 16 bits, and a long at least 32 bits. A char can hold a character of the machine’s character set. The char type is supposed to be chosen by the implementation to be the most suitable type for holding and manipulating characters on a given computer; it is typically an 8-bit byte. Similarly, the int type is supposed to be chosen to be the most suitable for holding and manipulating integers on a given computer; it is typically a 4-byte (32-bit) word. It is unwise to assume more. For example, there are machines with 32-bit chars. It is extremely unwise to assume that the size of an int is the same as the size of a pointer; many machines (‘‘64-bit architec- tures’’) have pointers that are larger than integers. Note that it is not guaranteed that sizeof(long)<sizeof(long long) or that sizeof(double)<sizeof(long double). Some implementation-defined aspects of fundamental types can be found by a simple use of sizeof, and more can be found in <limits>. For example: #include <limits> // §40.2 #include <iostream> int main() { cout << "size of long " << sizeof(1L) << '\n'; cout << "size of long long " << sizeof(1LL) << '\n'; cout << "largest float == " << std::numeric_limits<float>::max() << '\n'; cout << "char is signed == " << std::numeric_limits<char>::is_signed << '\n'; } The functions in <limits> (§40.2) are constexpr (§10.4) so that they can be used without run-time overhead and in contexts that require a constant expression. The fundamental types can be mixed freely in assignments and expressions. Wherever possible, values are converted so as not to lose information (§10.5). If a value v can be represented exactly in a variable of type T, a conversion of v to T is value- preserving. Conversions that are not value-preserving are best avoided (§2.2 .2, §10.5 .2 .6). If you need a specific size of integer, say, a 16-bit integer, you can #include the standard header <cstdint> that defines a variety of types (or rather type aliases; §6.5). For example: int16_t x {0xaabb}; // 2 bytes int64_t xxxx {0xaaaabbbbccccdddd}; // 8 bytes int_least16_t y; // at least 2 bytes (just like int) int_least32_t yy // at least 4 bytes (just like long) int_fast32_t z; // the fastest int type with at least 4 bytes The standard header <cstddef> defines an alias that is very widely used in both standard-library dec- larations and user code: size_t is an implementation-defined unsigned integer type that can hold the size in bytes of every object. Consequently, it is used where we need to hold an object size. For example: void∗ allocate(size_t n); // get n bytes Similarly, <cstddef> defines the signed integer type ptrdiff_t for holding the result of subtracting two pointers to get a number of elements.
ptg10564057 Section 6.2 .9 Alignment 151 6.2.9 Alignment An object doesn’t just need enough storage to hold its representation. In addition, on some machine architectures, the bytes used to hold it must have proper alignment for the hardware to access it efficiently (or in extreme cases to access it at all). For example, a 4-byte int often has to be aligned on a word (4-byte) boundary, and sometimes an 8-byte double has to be aligned on a word (8-byte) boundary. Of course, this is all very implementation specific, and for most programmers completely implicit. You can write good C++ code for decades without needing to be explicit about alignment. Where alignment most often becomes visible is in object layouts: sometimes structs contain ‘‘holes’’ to improve alignment (§8.2 .1). The alignof() operator returns the alignment of its argument expression. For example: auto ac = alignof('c'); // the alignment of a char auto ai = alignof(1); // the alignment of an int auto ad = alignof(2.0); // the alignment of a double int a[20]; auto aa = alignof(a); // the alignment of an int Sometimes, we have to use alignment in a declaration, where an expression, such as alignof(x+y) is not allowed. Instead, we can use the type specifier alignas: alignas(T) means ‘‘align just like a T.’’ For example, we can set aside uninitialized storage for some type X like this: void user(const vector<X>& vx) { constexpr int bufmax = 1024; alignas(X) buffer[bufmax]; // uninitialized const int max = min(vx.size(),bufmax/sizeof(X)); uninitialized_copy(vx.begin(),vx.begin()+max,buffer); // ... } 6.3 Declarations Before a name (identifier) can be used in a C++ program, it must be declared. That is, its type must be specified to inform the compiler what kind of entity the name refers to. For example: char ch; string s; auto count = 1; const double pi {3.1415926535897}; extern int error_number; const char∗ name = "Njal"; const char∗ season[] = { "spring", "summer", "fall", "winter" }; vector<string> people { name, "Skarphedin", "Gunnar" };
ptg10564057 152 Types and Declarations Chapter 6 struct Date { int d, m, y; }; int day(Date∗ p) { return p−>d; } double sqrt(double); template<class T> T abs(T a) { return a<0 ? −a : a; } constexpr int fac(int n) { return (n<2)?1:n∗fac(n−1); } // possible compile-time evaluation (§2.2 .3) constexpr double zz { ii∗fac(7) }; // compile-time initialization using Cmplx = std::complex<double>; // type alias (§3.4 .5, §6.5) struct User; // type name enum class Beer { Carlsberg, Tuborg, Thor }; namespace NS { int a; } As can be seen from these examples, a declaration can do more than simply associate a type with a name. Most of these declarations are also definitions. A definition is a declaration that supplies all that is needed in a program for the use of an entity. In particular, if it takes memory to represent something, that memory is set aside by its definition. A different terminology deems declarations parts of an interface and definitions parts of an implementation. When taking that view, we try to compose interfaces out of declarations that can be replicated in separate files (§15.2 .2); definitions that set aside memory do not belong in interfaces. Assuming that these declarations are in the global scope (§6.3 .4), we have: char ch; // set aside memory for a char and initialize it to 0 auto count = 1; // set aside memory for an int initialized to 1 const char∗ name = "Njal"; // set aside memory for a pointer to char // set aside memory for a string literal "Njal" // initialize the pointer with the address of that string literal struct Date { int d, m, y; }; // Date is a struct with three members int day(Date∗ p) { return p−>d; } // day is a function that executes the specified code using Point = std::complex<short>;// Point is a name for std::complex<short> Of the declarations above, only three are not also definitions: double sqrt(double); // function declaration extern int error_number; // variable declaration struct User; // type name declaration That is, if used, the entity they refer to must be defined elsewhere. For example: double sqrt(double d) { /* ... */ } int error_number = 1; struct User { /* ... */ }; There must always be exactly one definition for each name in a C++ program (for the effects of #include, see §15.2 .3). However, there can be many declarations. All declarations of an entity must agree on its type. So, this fragment has two errors: int count; int count; // error: redefinition
ptg10564057 Section 6.3 Declarations 153 extern int error_number; extern short error_number; // error: type mismatch This has no errors (for the use of extern, see §15.2): extern int error_number; extern int error_number; // OK: redeclaration Some definitions explicitly specify a ‘‘value’’ for the entities they define. For example: struct Date { int d, m, y; }; using Point = std::complex<short>; // Point is a name for std::complex<short> int day(Date∗ p) { return p−>d; } const double pi {3.1415926535897}; For types, aliases, templates, functions, and constants, the ‘‘value’’ is permanent. For non-const data types, the initial value may be changed later. For example: void f() { int count {1}; // initialize count to 1 const char∗ name {"Bjarne"}; // name is a variable that points to a constant (§7.5) count = 2; // assign 2 to count name = "Marian"; } Of the definitions, only two do not specify values: char ch; string s; See §6.3 .5 and §17.3 .3 for explanations of how and when a variable is assigned a default value. Any declaration that specifies a value is a definition. 6.3.1 The Structure of Declarations The structure of a declaration is defined by the C++ grammar (§iso.A). This grammar evolved over four decades, starting with the early C grammars, and is quite complicated. However, without too many radical simplifications, we can consider a declaration as having five parts (in order): • Optional prefix specifiers (e.g ., static or virtual) • A base type (e.g ., vector<double> or const int) • A declarator optionally including a name (e.g ., p[7], n,or∗(∗)[]) • Optional suffix function specifiers (e.g ., const or noexcept) • An optional initializer or function body (e.g ., ={7,5,3} or {return x;}) Except for function and namespace definitions, a declaration is terminated by a semicolon. Con- sider a definition of an array of C-style strings: const char∗ kings[] = { "Antigonus", "Seleucus", "Ptolemy" }; Here, the base type is const char, the declarator is ∗kings[], and the initializer is the = followed by the {}-list. A specifier is an initial keyword, such as virtual (§3.2.3, §20.3 .2), extern (§15.2), or constexpr (§2.2 .3), that specifies some non-type attribute of what is being declared.
ptg10564057 154 Types and Declarations Chapter 6 A declarator is composed of a name and optionally some declarator operators. The most com- mon declarator operators are: Declarator Operators prefix ∗ pointer prefix ∗const constant pointer prefix ∗volatile volatile pointer prefix & lvalue reference (§7.7 .1) prefix && rvalue reference (§7.7 .2) prefix auto function (using suffix return type) postfix [] array postfix () function postfix −> returns from function Their use would be simple if they were all either prefix or postfix. However, ∗, [], and () were designed to mirror their use in expressions (§10.3). Thus, ∗ is prefix and [] and () are postfix. The postfix declarator operators bind tighter than the prefix ones. Consequently, char∗kings[] is an array of pointers to char, whereas char(∗kings)[] is a pointer to an array of char. We have to use parenthe- ses to express types such as ‘‘pointer to array’’ and ‘‘pointer to function’’; see the examples in §7.2 . Note that the type cannot be left out of a declaration. For example: const c = 7; // error: no type gt(int a, int b) // error: no return type { return (a>b) ? a : b; } unsigned ui; // OK: ‘‘unsigned’’means ‘‘unsigned int’’ long li; // OK: ‘‘long’’ means ‘‘long int’’ In this, standard C++ differs from early versions of C and C++ that allowed the first two examples by considering int to be the type when none was specified (§44.3). This ‘‘implicit int’’ rule was a source of subtle errors and much confusion. Some types have names composed out of multiple keywords, such as long long and volatile int. Some type names don’t even look much like names, such as decltype(f(x)) (the return type of a call f(x); §6.3 .6 .3). The volatile specifier is described in §41.4 . The alignas() specifier is described in §6.2 .9. 6.3.2 Declaring Multiple Names It is possible to declare several names in a single declaration. The declaration simply contains a list of comma-separated declarators. For example, we can declare two integers like this: int x, y; //intx;inty;
ptg10564057 Section 6.3 .2 Declaring Multiple Names 155 Operators apply to individual names only – and not to any subsequent names in the same declara- tion. For example: int∗ p, y; // int* p; int y; NOT int* y; int x, ∗q; // int x; int* q; int v[10], ∗pv; // int v[10]; int* pv; Such declarations with multiple names and nontrivial declarators make a program harder to read and should be avoided. 6.3.3 Names A name (identifier) consists of a sequence of letters and digits. The first character must be a letter. The underscore character, _, is considered a letter. C++ imposes no limit on the number of charac- ters in a name. However, some parts of an implementation are not under the control of the compiler writer (in particular, the linker), and those parts, unfortunately, sometimes do impose limits. Some run-time environments also make it necessary to extend or restrict the set of characters accepted in an identifier. Extensions (e.g ., allowing the character $ in a name) yield nonportable programs. A C++ keyword (§6.3 .3 .1), such as new or int, cannot be used as a name of a user-defined entity. Examples of names are: hello this_is_a_most_unusually_long_identifier_that_is_better_avoided DEFINED foO bAr u_name HorseSense var0 var1 CLASS _class ___ Examples of character sequences that cannot be used as identifiers are: 012 a fool $sys class 3var pay.due foõbar .name if Nonlocal names starting with an underscore are reserved for special facilities in the implementation and the run-time environment, so such names should not be used in application programs. Simi- larly, names starting with a double underscore (__) or an underscore followed by an uppercase letter (e.g., _Foo) are reserved (§iso.17.6.4 .3). When reading a program, the compiler always looks for the longest string of characters that could make up a name. Hence, var10 is a single name, not the name var followed by the number 10. Also, elseif is a single name, not the keyword else followed by the keyword if. Uppercase and lowercase letters are distinct, so Count and count are different names, but it is often unwise to choose names that differ only by capitalization. In general, it is best to avoid names that differ only in subtle ways. For example, in some fonts, the uppercase ‘‘o’’ (O) and zero (0) can be hard to tell apart, as can the lowercase ‘‘L’’ (l), uppercase ‘‘i’’ (I), and one (1). Conse- quently, l0, lO, l1, ll, and I1l are poor choices for identifier names. Not all fonts have the same prob- lems, but most have some. Names from a large scope ought to have relatively long and reasonably obvious names, such as vector, Window_with_border, and Department_number. However, code is clearer if names used only in a small scope have short, conventional names such as x, i, and p. Functions (Chapter 12), classes (Chapter 16), and namespaces (§14.3 .1) can be used to keep scopes small. It is often useful to keep frequently used names relatively short and reserve really long names for infrequently used entities.
ptg10564057 156 Types and Declarations Chapter 6 Choose names to reflect the meaning of an entity rather than its implementation. For example, phone_book is better than number_vector even if the phone numbers happen to be stored in a vector (§4.4). Do not encode type information in a name (e.g ., pcname for a name that’s a char∗ or icount for a count that’s an int) as is sometimes done in languages with dynamic or weak type systems: • Encoding types in names lowers the abstraction level of the program; in particular, it pre- vents generic programming (which relies on a name being able to refer to entities of differ- ent types). • The compiler is better at keeping track of types than you are. • If you want to change the type of a name (e.g ., use a std::string to hold the name), you’ll have to change every use of the name (or the type encoding becomes a lie). • Any system of type abbreviations you can come up with will become overelaborate and cryptic as the variety of types you use increases. Choosing good names is an art. Try to maintain a consistent naming style. For example, capitalize names of user-defined types and start names of non-type entities with a lowercase letter (for example, Shape and current_token). Also, use all capitals for macros (if you must use macros (§12.6); for example, HACK) and never for non-macros (not even for non-macro constants). Use underscores to separate words in an identifier; number_of_elements is more readable than numberOfElements. However, consistency is hard to achieve because programs are typically composed of fragments from different sources and several different reasonable styles are in use. Be consistent in your use of abbreviations and acronyms. Note that the language and the standard library use lowercase for types; this can be seen as a hint that they are part of the standard. 6.3 .3.1 Keywords The C++ keywords are: C++ Keywords alignas alignof and and_eq asm auto bitand bitor bool break case catch char char16_t char32_t class compl const constexpr const_cast continue decltype default delete do double dynamic_cast else enum explicit extern false float for friend goto if inline int long mutable namespace new noexcept not not_eq nullptr operator or or_eq private protected public register reinterpret_cast return short signed sizeof static static_assert static_cast struct switch template this thread_local throw true try typedef typeid typename union unsigned using virtual void volatile wchar_t while xor xor_eq In addition, the word export is reserved for future use.
ptg10564057 Section 6.3 .4 Scope 157 6.3.4 Scope A declaration introduces a name into a scope; that is, a name can be used only in a specific part of the program text. • Local scope: A name declared in a function (Chapter 12) or lambda (§11.4) is called a local name. Its scope extends from its point of declaration to the end of the block in which its de- claration occurs. A block is a section of code delimited by a {} pair. Function and lambda parameter names are considered local names in the outermost block of their function or lambda. • Class scope: A name is called a member name (or a class member name) if it is defined in a class outside any function, class (Chapter 16), enum class (§8.4 .1), or other namespace. Its scope extends from the opening { of the class declaration to the end of the class declaration. • Namespace scope: A name is called a namespace member name if it is defined in a name- space (§14.3 .1) outside any function, lambda (§11.4), class (Chapter 16), enum class (§8.4 .1), or other namespace. Its scope extends from the point of declaration to the end of its namespace. A namespace name may also be accessible from other translation units (§15.2). • Global scope: A name is called a global name if it is defined outside any function, class (Chapter 16), enum class (§8.4 .1), or namespace (§14.3 .1). The scope of a global name extends from the point of declaration to the end of the file in which its declaration occurs. A global name may also be accessible from other translation units (§15.2). Technically, the global namespace is considered a namespace, so a global name is an example of a name- space member name. • Statement scope: A name is in a statement scope if it is defined within the () part of a for-, while-, if-, or switch-statement. Its scope extends from its point of declaration to the end of its statement. All names in statement scope are local names. • Function scope: A label (§9.6) is in scope from its point of declaration until the end of the function. A declaration of a name in a block can hide a declaration in an enclosing block or a global name. That is, a name can be redefined to refer to a different entity within a block. After exit from the block, the name resumes its previous meaning. For example: int x; // global x void f() { int x; // local x hides global x x=1; //assign to local x { int x; // hides first local x x=2; //assign to second local x } x=3; //assign to first local x } int∗p=&x; // take address of global x
ptg10564057 158 Types and Declarations Chapter 6 Hiding names is unavoidable when writing large programs. However, a human reader can easily fail to notice that a name has been hidden (also known as shadowed). Because such errors are rela- tively rare, they can be very difficult to find. Consequently, name hiding should be minimized. Using names such as i and x for global variables or for local variables in a large function is asking for trouble. A hidden global name can be referred to using the scope resolution operator, ::. For example: int x; void f2() { intx=1; //hideglobalx ::x = 2; // assign to global x x=2; //assign to local x // ... } There is no way to use a hidden local name. The scope of a name that is not a class member starts at its point of declaration, that is, after the complete declarator and before the initializer. This implies that a name can be used even to specify its own initial value. For example: intx=97; void f3() { intx=x; // perverse: initialize x with its own (uninitialized) value } A good compiler warns if a variable is used before it has been initialized. It is possible to use a single name to refer to two different objects in a block without using the :: operator. For example: intx=11; void f4() // perverse: use of two different objects both called x in a single scope { inty=x; //useglobalx:y=11 intx=22; y=x; //use local x: y = 22 } Again, such subtleties are best avoided. The names of function arguments are considered declared in the outermost block of a function. For example: void f5(int x) { int x; // error }
ptg10564057 Section 6.3 .4 Scope 159 This is an error because x is defined twice in the same scope. Names introduced in a for-statement are local to that statement (in statement scope). This allows us to use conventional names for loop variables repeatedly in a function. For example: void f(vector<string>& v, list<int>& lst) { for (const auto& x : v) cout << x << '\n'; for (auto x : lst) cout << x << '\n'; for (int i = 0, i!=v.size(), ++i) cout << v[i] << '\n'; for(autoi:{1,2,3,4,5,6,7})cout<<i<<'\n'; } This contains no name clashes. A declaration is not allowed as the only statement on the branch of an if-statement (§9.4.1). 6.3.5 Initialization If an initializer is specified for an object, that initializer determines the initial value of an object. An initializer can use one of four syntactic styles: X a1 {v}; Xa2={v}; Xa3=v; X a4(v); Of these, only the first can be used in every context, and I strongly recommend its use. It is clearer and less error-prone than the alternatives. However, the first form (used for a1) is new in C++11, so the other three forms are what you find in older code. The two forms using = are what you use in C. Old habits die hard, so I sometimes (inconsistently) use = when initializing a simple variable with a simple value. For example: intx1=0; char c1 = 'z'; However, anything much more complicated than that is better done using {}. Initialization using {}, list initialization, does not allow narrowing (§iso.8 .5 .4). That is: • An integer cannot be converted to another integer that cannot hold its value. For example, char to int is allowed, but not int to char. • A floating-point value cannot be converted to another floating-point type that cannot hold its value. For example, float to double is allowed, but not double to float. • A floating-point value cannot be converted to an integer type. • An integer value cannot be converted to a floating-point type. For example: void f(double val, int val2) { int x2 = val; // if val==7.9, x2 becomes 7 char c2 = val2; // if val2==1025, c2 becomes 1
ptg10564057 160 Types and Declarations Chapter 6 int x3 {val}; // error: possible truncation char c3 {val2}; // error: possible narrowing char c4 {24}; // OK: 24 can be represented exactly as a char char c5 {264}; // error (assuming 8-bit chars): 264 cannot be represented as a char int x4 {2.0}; // error: no double to int value conversion // ... } See §10.5 for the conversion rules for built-in types. There is no advantage to using {} initialization, and one trap, when using auto to get the type determined by the initializer. The trap is that if the initializer is a {}-list, we may not want its type deduced (§6.3 .6 .2). For example: auto z1 {99}; // z1 is an initializer_list<int> autoz2=99; //z2isanint So prefer = when using auto. It is possible to define a class so that an object can be initialized by a list of values and alterna- tively be constructed given a couple of arguments that are not simply values to be stored. The clas- sical example is a vector of integers: vector<int> v1 {99}; // v1 is a vector of 1 element with the value 99 vector<int> v2(99); // v2 is a vector of 99 elements each with the default value 0 I use the explicit invocation of a constructor, (99), to get the second meaning. Most types do not offer such confusing alternatives – even most vectors do not; for example: vector<string> v1{"hello!"}; // v1 is a vector of 1 element with the value "hello!" vector<string> v2("hello!"); // error: no vector constructor takes a string literal So, prefer {} initialization over alternatives unless you have a strong reason not to. The empty initializer list, {}, is used to indicate that a default value is desired. For example: int x4 {}; // x4 becomes 0 double d4 {}; // d4 becomes 0.0 char∗ p {}; // p becomes nullptr vector<int> v4{}; // v4 becomes the empty vector string s4 {}; // s4 becomes "" Most types have a default value. For integral types, the default value is a suitable representation of zero. For pointers, the default value is nullptr (§7.2.2). For user-defined types, the default value (if any) is determined by the type’s constructors (§17.3 .3). For user-defined types, there can be a distinction between direct initialization (where implicit conversions are allowed) and copy initialization (where they are not); see §16.2 .6 . Initialization of particular kinds of objects is discussed where appropriate: • Pointers: §7.2 .2, §7.3 .2, §7.4 • References: §7.7 .1 (lvalues), §7.7 .2 (rvalues)
ptg10564057 Section 6.3 .5 Initialization 161 • Arrays: §7.3 .1, §7.3 .2 • Constants: §10.4 • Classes: §17.3 .1 (not using constructors), §17.3 .2 (using constructors), §17.3 .3 (default), §17.4 (member and base), §17.5 (copy and move) • User-defined containers: §17.3 .4 6.3 .5.1 Missing Initializers For many types, including all built-in types, it is possible to leave out the initializer. If you do that – and that has unfortunately been common – the situation is more complicated. If you don’t like the complications, just initialize consistently. The only really good case for an uninitialized vari- able is a large input buffer. For example: constexpr int max = 1024∗1024; char buf[max]; some_stream.get(buf,max); // read at most max characters into buf We could easily have initialized buf: char buf[max] {}; // initialize every char to 0 By redundantly initializing, we would have suffered a performance hit which just might have been significant. Avoid such low-level use of buffers where you can, and don’t leave such buffers unini- tialized unless you know (e.g ., from measurement) that the optimization compared to using an ini- tialized array is significant. If no initializer is specified, a global (§6.3 .4), namespace (§14.3 .1), local static (§12.1 .8), or static member (§16.2 .12) (collectively called static objects) is initialized to {} of the appropriate type. For example: int a; // means ‘‘int a{};’’ so that a becomes 0 double d; // means ‘‘double d{};’’ so that d becomes 0.0 Local variables and objects created on the free store (sometimes called dynamic objects or heap objects; §11.2) are not initialized by default unless they are of user-defined types with a default constructor (§17.3 .3). For example: void f() { int x; // x does not have a well-defined value char buf[1024]; // buf[i] does not have a well-defined value int∗ p {new int}; // *p does not have a well-defined value char∗ q {new char[1024]}; // q[i] does not have a well-defined value string s; // s=="" because of string’s default constructor vector<char> v; // v=={} because of vector’s default constructor string∗ ps {new string}; // *ps is "" because of string’s default constructor // ... }
ptg10564057 162 Types and Declarations Chapter 6 If you want initialization of local variables of built-in type or objects of built-in type created with new, use {}. For example: void ff() { int x {}; // x becomes 0 char buf[1024]{}; // buf[i] becomes 0 for all i int∗ p {new int{10}}; // *p becomes 10 char∗ q {new char[1024]{}}; // q[i] becomes 0 for all i // ... } A member of an array or a class is default initialized if the array or structure is. 6.3 .5.2 Initializer Lists So far, we have considered the cases of no initializer and one initializer value. More complicated objects can require more than one value as an initializer. This is primarily handled by initializer lists delimited by { and }. For example: inta[]={1,2}; // array initializer struct S { int x, string s }; Ss={1, "Helios"}; // struct initializer complex<double> z = { 0, pi }; // use constructor vector<double> v = { 0.0, 1.1, 2.2, 3.3 }; // use list constructor For C-style initialization of arrays, see §7.3 .1 . For C-style structures, see §8.2 . For user-defined types with constructors, see §2.3 .2 or §16.2 .5 . For initializer-list constructors, see §17.3.4 . In the cases above, the = is redundant. However, some prefer to add it to emphasize that a set of values are used to initialize a set of member variables. In some cases, function-style argument lists can also be used (§2.3, §16.2 .5). For example: complex<double> z(0,pi); // use constructor vector<double> v(10,3.3); // use constructor: v gets 10 elements initialized to 3.3 In a declaration, an empty pair of parentheses, (), always means ‘‘function’’ (§12.1). So, if you want to be explicit about ‘‘use default initialization’’ you need {}. For example: complex<double> z1(1,2); // function-style initializer (initialization by constructor) complex<double> f1(); // function declaration complex<double> z2 {1,2}; // initialization by constructor to {1,2} complex<double> f2 {}; // initialization by constructor to the default value {0,0} Note that initialization using the {} notation does not narrow (§6.3 .5). When using auto,a{}-list has its type deduced to std::initializer_list<T>. For example: auto x1 {1,2,3,4}; // x1 is an initializer_list<int> auto x2 {1.0, 2.25, 3.5 }; // x2 is an initializer_list of<double> auto x3 {1.0,2}; // error: cannot deduce the type of {1.0,2} (§6.3 .6 .2)
ptg10564057 Section 6.3 .5 .2 Initializer Lists 163 6.3.6 Deducing a Type: auto and decltype() The language provides two mechanisms for deducing a type from an expression: • auto for deducing a type of an object from its initializer; the type can be the type of a vari- able, a const,oraconstexpr. • decltype(expr) for deducing the type of something that is not a simple initializer, such as the return type for a function or the type of a class member. The deduction done here is very simple: auto and decltype() simply report the type of an expression already known to the compiler. 6.3 .6.1 The auto Type Specifier When a declaration of a variable has an initializer, we don’t need to explicitly specify a type. Instead, we can let the variable have the type of its initializer. Consider: int a1 = 123; char a2 = 123; auto a3 = 123; // the type of a3 is ‘‘int’’ The type of the integer literal 123 is int,soa3 is an int. That is, auto is a placeholder for the type of the initializer. There is not much advantage in using auto instead of int for an expression as simple as 123. The harder the type is to write and the harder the type is to know, the more useful auto becomes. For example: template<class T> void f1(vector<T>& arg) { for (vector<T>::iterator p = arg.begin(); p!=arg.end(); ++p) ∗p=7; for (auto p = arg.begin(); p!=arg.end(); ++p) ∗p=7; } The loop using auto is the more convenient to write and the easier to read. Also, it is more resilient to code changes. For example, if I changed arg to be a list, the loop using auto would still work cor- rectly whereas the first loop would need to be rewritten. So, unless there is a good reason not to, use auto in small scopes. If a scope is large, mentioning a type explicitly can help localize errors. That is, compared to using a specific type, using auto can delay the detection of type errors. For example: void f(double d) { constexpr auto max = d+7; int a[max]; // error: array bound not an integer // ... } If auto causes surprises, the best cure is typically to make functions smaller, which most often is a good idea anyway (§12.1).
ptg10564057 164 Types and Declarations Chapter 6 We can decorate a deduced type with specifiers and modifiers (§6.3 .1), such as const and & (ref- erence; §7.7). For example: void f(vector<int>& v) { for(constauto&x:v){ //xisaconstint& // ... } } Here, auto is determined by the element type of v, that is, int. Note that the type of an expression is never a reference because references are implicitly deref- erenced in expressions (§7.7). For example: void g(int& v) { autox=v; //xisanint(notanint&) auto&y=v; //yisanint& } 6.3 .6.2 auto and {}-lists When we explicitly mention the type of an object we are initializing, we have two types to con- sider: the type of the object and the type of the initializer. For example: char v1 = 12345; // 12345 is an int int v2 = 'c'; //'c'isachar Tv3=f(); By using the {}-initializer syntax for such definitions, we minimize the chances for unfortunate con- versions: char v1 {12345}; // error: narrowing int v2 {'c'}; // fine: implicit char->int conversion T v3 {f()}; // works if and only if the type of f() can be implicitly converted to a T When we use auto, there is only one type involved, the type of the initializer, and we can safely use the = syntax: autov1=12345; //v1isanint auto v2 = 'c'; //v2isachar auto v3 = f(); // v3 is of some appropriate type In fact, it can be an advantage to use the = syntax with auto, because the {}-list syntax might sur- prise someone: auto v1 {12345}; // v1 is a list of int auto v2 {'c'}; //v2isalistofchar auto v3 {f()}; // v3 is a list of some appropriate type This is logical. Consider:
ptg10564057 Section 6.3 .6 .2 auto and {}-lists 165 auto x0 {}; // error: cannot deduce a type auto x1 {1}; // list of int with one element auto x2 {1,2}; // list of int with two elements auto x3 {1,2,3}; // list of int with three elements The type of a homogeneous list of elements of type T is taken to be of type initializer_list<T> (§3.2 .1 .3, §11.3 .3). In particular, the type of x1 is not deduced to be int. Had it been, what would be the types of x2 and x3? Consequently, I recommend using = rather than {} for objects specified auto whenever we don’t mean ‘‘list.’’ 6.3 .6.3 The decltype() Specifier We can use auto when we have a suitable initializer. But sometimes, we want to have a type deduced without defining an initialized variable. Then, we can use a declaration type specifier: decltype(expr) is the declared type of expr. This is mostly useful in generic programming. Consider writing a function that adds two matrices with potentially different element types. What should be the type of the result of the addition? A matrix, of course, but what might its element type be? The obvious answer is that the element type of the sum is the type of the sum of the elements. So, I can declare: template<class T, class U> auto operator+(const Matrix<T>& a, const Matrix<U>& b) −> Matrix<decltype(T{}+U{})>; I use the suffix return type syntax (§12.1) to be able to express the return type in terms of the argu- ments: Matrix<decltype(T{}+U{})>. That is, the result is a Matrix with the element type being what you get from adding a pair of elements from the argument Matrixes: T{}+U{}. In the definition, I again need decltype() to express Matrix’s element type: template<class T, class U> auto operator+(const Matrix<T>& a, const Matrix<U>& b) −> Matrix<decltype(T{}+U{})> { Matrix<decltype(T{}+U{})> res; for (int i=0; i!=a.rows(); ++i) for (int j=0; j!=a.cols(); ++j) res(i,j) += a(i,j) + b(i,j); return res; } 6.4 Objects and Values We can allocate and use objects that do not have names (e.g ., created using new), and it is possible to assign to strange-looking expressions (e.g ., ∗p[a+10]=7). Consequently, we need a name for ‘‘something in memory.’’ This is the simplest and most fundamental notion of an object. That is, an object is a contiguous region of storage; an lvalue is an expression that refers to an object. The word ‘‘lvalue’’ was originally coined to mean ‘‘something that can be on the left-hand side of an assignment.’’ However, not every lvalue may be used on the left-hand side of an assignment; an
ptg10564057 166 Types and Declarations Chapter 6 lvalue can refer to a constant (§7.7). An lvalue that has not been declared const is often called a modifiable lvalue. This simple and low-level notion of an object should not be confused with the notions of class object and object of polymorphic type (§3.2 .2, §20.3 .2). 6.4.1 Lvalues and Rvalues To complement the notion of an lvalue, we have the notion of an rvalue. Roughly, rvalue means ‘‘a value that is not an lvalue,’’ such as a temporary value (e.g ., the value returned by a function). If you need to be more technical (say, because you want to read the ISO C++ standard), you need a more refined view of lvalue and rvalue. There are two properties that matter for an object when it comes to addressing, copying, and moving: • Has identity: The program has the name of, pointer to, or reference to the object so that it is possible to determine if two objects are the same, whether the value of the object has changed, etc. • Movable: The object may be moved from (i.e., we are allowed to move its value to another location and leave the object in a valid but unspecified state, rather than copying; §17.5). It turns out that three of the four possible combinations of those two properties are needed to pre- cisely describe the C++ language rules (we have no need for objects that do not have identity and cannot be moved). Using ‘‘m for movable’’ and ‘‘i for has identity,’’ we can represent this classifi- cation of expressions graphically: lvalue {i&!m} xvalue {i&m} prvalue {!i&m} glvalue {i} rvalue {m} So, a classical lvalue is something that has identity and cannot be moved (because we could exam- ine it after a move), and a classical rvalue is anything that we are allowed to move from. The other alternatives are prvalue (‘‘pure rvalue’’), glvalue (‘‘generalized lvalue’’), and xvalue (‘‘x’’ for ‘‘ex- traordinary’’ or ‘‘expert only’’; the suggestions for the meaning of this ‘‘x’’ have been quite imagi- native). For example: void f(vector<string>& vs) { vector<string>& v2 = std::move(vs); // move vs to v2 // ... } Here, std::move(vs) is an xvalue: it clearly has identity (we can refer to it as vs), but we have explic- itly given permission for it to be moved from by calling std::move() (§3.3 .2, §35.5.1). For practical programming, thinking in terms of rvalue and lvalue is usually sufficient. Note that every expression is either an lvalue or an rvalue, but not both. 6.4.2 Lifetimes of Objects The lifetime of an object starts when its constructor completes and ends when its destructor starts executing. Objects of types without a declared constructor, such as an int, can be considered to have default constructors and destructors that do nothing.
ptg10564057 Section 6.4 .2 Lifetimes of Objects 167 We can classify objects based on their lifetimes: • Automatic: Unless the programmer specifies otherwise (§12.1 .8, §16.2 .12), an object declared in a function is created when its definition is encountered and destroyed when its name goes out of scope. Such objects are sometimes called automatic objects. In a typical implementation, automatic objects are allocated on the stack; each call of the function gets its own stack frame to hold its automatic objects. • Static: Objects declared in global or namespace scope (§6.3 .4) and statics declared in func- tions (§12.1 .8) or classes (§16.2.12) are created and initialized once (only) and ‘‘live’’ until the program terminates (§15.4 .3). Such objects are called static objects. A static object has the same address throughout the life of a program execution. Static objects can cause seri- ous problems in a multi-threaded program because they are shared among all threads and typically require locking to avoid data races (§5.3 .1, §42.3). • Free store: Using the new and delete operators, we can create objects whose lifetimes are controlled directly (§11.2). • Temporary objects (e.g ., intermediate results in a computation or an object used to hold a value for a reference to const argument): their lifetime is determined by their use. If they are bound to a reference, their lifetime is that of the reference; otherwise, they ‘‘live’’ until the end of the full expression of which they are part. A full expression is an expression that is not part of another expression. Typically, temporary objects are automatic. • Thread-local objects; that is, objects declared thread_local (§42.2 .8): such objects are cre- ated when their thread is and destroyed when their thread is. Static and automatic are traditionally referred to as storage classes. Array elements and nonstatic class members have their lifetimes determined by the object of which they are part. 6.5 Type Aliases Sometimes, we need a new name for a type. Possible reasons include: • The original name is too long, complicated, or ugly (in some programmer’s eyes). • A programming technique requires different types to have the same name in a context. • A specific type is mentioned in one place only to simplify maintenance. For example: using Pchar = char∗;/ / pointer to character using PF = int(∗)(double); // pointer to function taking a double and returning an int Similar types can define the same name as a member alias: template<class T> class vector { using value_type = T; // every container has a value_type // ... };
ptg10564057 168 Types and Declarations Chapter 6 template<class T> class list { using value_type = T; // every container has a value_type // ... }; For good and bad, type aliases are synonyms for other types rather than distinct types. That is, an alias refers to the type for which it is an alias. For example: Pchar p1 = nullptr; //p1isachar* char∗ p3 = p1; // fine People who would like to have distinct types with identical semantics or identical representation should look at enumerations (§8.4) and classes (Chapter 16). An older syntax using the keyword typedef and placing the name being declared where it would have been in a declaration of a variable can equivalently be used in many contexts. For example: typedef int int32_t; // equivalent to ‘‘using int32_t = int;’’ typedef short int16_t; // equivalent to ‘‘using int16_t = short;’’ typedef void(∗PtoF)(int); // equivalent to ‘‘using PtoF = void(*)(int);’’ Aliases are used when we want to insulate our code from details of the underlying machine. The name int32_t indicates that we want it to represent a 32-bit integer. Having written our code in terms of int32_t, rather than ‘‘plain int,’’ we can port our code to a machine with sizeof(int)==2 by redefining the single occurrence of int32_t in our code to use a longer integer: using int32_t = long; The _t suffix is conventional for aliases (‘‘typedefs’’). The int16_t, int32_t, and other such aliases can be found in <stdint> (§43.7). Note that naming a type after its representation rather than its pur- pose is not necessarily a good idea (§6.3 .3). The using keyword can also be used to introduce a template alias (§23.6). For example: template<typename T> using Vector = std::vector<T, My_allocator<T>>; We cannot apply type specifiers, such as unsigned, to an alias. For example: using Char = char; using Uchar = unsigned Char; // error using Uchar = unsigned char; // OK 6.6 Advice [1] For the final word on language definition issues, see the ISO C++ standard; §6.1. [2] Avoid unspecified and undefined behavior; §6.1 . [3] Isolate code that must depend on implementation-defined behavior; §6.1 . [4] Avoid unnecessary assumptions about the numeric value of characters; §6.2 .3 .2, §10.5 .2 .1 . [5] Remember that an integer starting with a 0 is octal; §6.2 .4 .1 .
ptg10564057 Section 6.6 Advice 169 [6] Avoid ‘‘magic constants’’; §6.2 .4.1 . [7] Avoid unnecessary assumptions about the size of integers; §6.2 .8 . [8] Avoid unnecessary assumptions about the range and precision of floating-point types; §6.2.8 . [9] Prefer plain char over signed char and unsigned char; §6.2 .3.1 . [10] Beware of conversions between signed and unsigned types; §6.2 .3 .1 . [11] Declare one name (only) per declaration; §6.3 .2. [12] Keep common and local names short, and keep uncommon and nonlocal names longer; §6.3 .3 . [13] Avoid similar-looking names; §6.3 .3 . [14] Name an object to reflect its meaning rather than its type; §6.3 .3. [15] Maintain a consistent naming style; §6.3 .3 . [16] Avoid ALL_CAPS names; §6.3.3 . [17] Keep scopes small; §6.3 .4 . [18] Don’t use the same name in both a scope and an enclosing scope; §6.3 .4 . [19] Prefer the {}-initializer syntax for declarations with a named type; §6.3 .5 . [20] Prefer the = syntax for the initialization in declarations using auto; §6.3 .5 . [21] Avoid uninitialized variables; §6.3 .5 .1 . [22] Use an alias to define a meaningful name for a built-in type in cases in which the built-in type used to represent a value might change; §6.5 . [23] Use an alias to define synonyms for types; use enumerations and classes to define new types; §6.5 .
ptg10564057 This page intentionally left blank
ptg10564057 7 Pointers, Arrays, and References The sublime and the ridiculous are often so nearly related that it is difficult to class them separately. – Thomas Paine • Introduction • Pointers void∗; nullptr • Arrays Array Initializers; String Literals • Pointers into Arrays Navigating Arrays; Multidimensional Arrays; Passing Arrays • Pointers and const • Pointers and Ownership • References Lvalue References; Rvalue References; References to References; Pointers and References • Advice 7.1 Introduction This chapter deals with the basic language mechanisms for referring to memory. Obviously, we can refer to an object by name, but in C++ (most) objects ‘‘have identity.’’ That is, they reside at a specific address in memory, and an object can be accessed if you know its address and its type. The language constructs for holding and using addresses are pointers and references.
ptg10564057 172 Pointers, Arrays, and References Chapter 7 7.2 Pointers For a type T, T∗ is the type ‘‘pointer to T.’’ That is, a variable of type T∗ can hold the address of an object of type T. For example: char c = 'a'; char∗ p = &c; // p holds the address of c; & is the address-of operator or graphically: &c 'a' p: c: The fundamental operation on a pointer is dereferencing, that is, referring to the object pointed to by the pointer. This operation is also called indirection. The dereferencing operator is (prefix) unary ∗. For example: char c = 'a'; char∗ p = &c; // p holds the address of c; & is the address-of operator char c2 = ∗p; // c2 == ’a’; * is the dereference operator The object pointed to by p is c, and the value stored in c is 'a', so the value of ∗p assigned to c2 is 'a'. It is possible to perform some arithmetic operations on pointers to array elements (§7.4). The implementation of pointers is intended to map directly to the addressing mechanisms of the machine on which the program runs. Most machines can address a byte. Those that can’t tend to have hardware to extract bytes from words. On the other hand, few machines can directly address an individual bit. Consequently, the smallest object that can be independently allocated and pointed to using a built-in pointer type is a char. Note that a bool occupies at least as much space as a char (§6.2 .8). To store smaller values more compactly, you can use the bitwise logical operations (§11.1.1), bit-fields in structures (§8.2 .7), or a bitset (§34.2 .2). The ∗, meaning ‘‘pointer to,’’ is used as a suffix for a type name. Unfortunately, pointers to arrays and pointers to functions need a more complicated notation: int∗ pi; // pointer to int char∗∗ ppc; // pointer to pointer to char int∗ ap[15]; // array of 15 pointers to ints int (∗fp)(char∗); // pointer to function taking a char* argument; returns an int int∗ f(char∗); // function taking a char* argument; returns a pointer to int See §6.3 .1 for an explanation of the declaration syntax and §iso.A for the complete grammar. Pointers to functions can be useful; they are discussed in §12.5 . Pointers to class members are presented in §20.6. 7.2.1 void∗ In low-level code, we occasionally need to store or pass along an address of a memory location without actually knowing what type of object is stored there. A void∗ is used for that. You can read void∗ as ‘‘pointer to an object of unknown type.’’
ptg10564057 Section 7.2 .1 void∗ 173 A pointer to any type of object can be assigned to a variable of type void∗, but a pointer to func- tion (§12.5) or a pointer to member (§20.6) cannot. In addition, a void∗ can be assigned to another void∗, void∗s can be compared for equality and inequality, and a void∗ can be explicitly converted to another type. Other operations would be unsafe because the compiler cannot know what kind of object is really pointed to. Consequently, other operations result in compile-time errors. To use a void∗, we must explicitly convert it to a pointer to a specific type. For example: void f(int∗ pi) { void∗ pv = pi; // ok: implicit conversion of int* to void* ∗pv; // error: can’t dereference void* ++pv; // error: can’t increment void* (the size of the object pointed to is unknown) int∗ pi2 = static_cast<int∗>(pv); // explicit conversion back to int* double∗ pd1 = pv; // error double∗ pd2 = pi; // error double∗ pd3 = static_cast<double∗>(pv); // unsafe (§11.5.2) } In general, it is not safe to use a pointer that has been converted (‘‘cast’’) to a type that differs from the type of the object pointed to. For example, a machine may assume that every double is allo- cated on an 8-byte boundary. If so, strange behavior could arise if pi pointed to an int that wasn’t allocated that way. This form of explicit type conversion is inherently unsafe and ugly. Conse- quently, the notation used, static_cast (§11.5 .2), was designed to be ugly and easy to find in code. The primary use for void∗ is for passing pointers to functions that are not allowed to make assumptions about the type of the object and for returning untyped objects from functions. To use such an object, we must use explicit type conversion. Functions using void∗ pointers typically exist at the very lowest level of the system, where real hardware resources are manipulated. For example: void∗ my_alloc(size_t n); // allocate n bytes from my special heap Occurrences of void∗s at higher levels of the system should be viewed with great suspicion because they are likely indicators of design errors. Where used for optimization, void∗ can be hidden behind a type-safe interface (§27.3 .1). Pointers to functions (§12.5) and pointers to members (§20.6) cannot be assigned to void∗s. 7.2.2 nullptr The literal nullptr represents the null pointer, that is, a pointer that does not point to an object. It can be assigned to any pointer type, but not to other built-in types: int∗ pi = nullptr; double∗ pd = nullptr; int i = nullptr; // error: i is not a pointer There is just one nullptr, which can be used for every pointer type, rather than a null pointer for each pointer type.
ptg10564057 174 Pointers, Arrays, and References Chapter 7 Before nullptr was introduced, zero (0) was used as a notation for the null pointer. For example: int∗ x=0;//x gets the value nullptr No object is allocated with the address 0, and 0 (the all-zeros bit pattern) is the most common repre- sentation of nullptr. Zero (0)isanint. However, the standard conversions (§10.5.2 .3) allow 0 to be used as a constant of pointer or pointer-to-member type. It has been popular to define a macro NULL to represent the null pointer. For example: int∗ p = NULL; // using the macro NULL However, there are differences in the definition of NULL in different implementations; for example, NULL might be 0 or 0L.InC,NULL is typically (void∗)0, which makes it illegal in C++ (§7.2 .1): int∗ p = NULL; // error: can’t assign a void* to an int* Using nullptr makes code more readable than alternatives and avoids potential confusion when a function is overloaded to accept either a pointer or an integer (§12.3 .1). 7.3 Arrays For a type T, T[size] is the type ‘‘array of size elements of type T.’’ The elements are indexed from 0 to size−1 . For example: float v[3]; // an array of three floats: v[0], v[1], v[2] char∗ a[32]; // an array of 32 pointers to char: a[0] .. a[31] You can access an array using the subscript operator, [], or through a pointer (using operator ∗ or operator []; §7.4). For example: void f() { int aa[10]; aa[6] = 9; // assign to aa’s 7th element int x = aa[99]; // undefined behavior } Access out of the range of an array is undefined and usually disastrous. In particular, run-time range checking is neither guaranteed nor common. The number of elements of the array, the array bound, must be a constant expression (§10.4). If you need variable bounds, use a vector (§4.4 .1, §31.4). For example: void f(int n) { int v1[n]; // error: array size not a constant expression vector<int> v2(n); // OK: vector with n int elements } Multidimensional arrays are represented as arrays of arrays (§7.4 .2). An array is C++’s fundamental way of representing a sequence of objects in memory. If what you want is a simple fixed-length sequence of objects of a given type in memory, an array is the ideal solution. For every other need, an array has serious problems.
ptg10564057 Section 7.3 Arrays 175 An array can be allocated statically, on the stack, and on the free store (§6.4 .2). For example: int a1[10]; // 10 ints in static storage void f() { int a2 [20]; // 20 ints on the stack int∗p = new int[40]; // 40 ints on the free store // ... } The C++ built-in array is an inherently low-level facility that should primarily be used inside the implementation of higher-level, better-behaved, data structures, such as the standard-library vector or array. There is no array assignment, and the name of an array implicitly converts to a pointer to its first element at the slightest provocation (§7.4). In particular, avoid arrays in interfaces (e.g ., as function arguments; §7.4 .3, §12.2 .2) because the implicit conversion to pointer is the root cause of many common errors in C code and C-style C++ code. If you allocate an array on the free store, be sure to delete[] its pointer once only and only after its last use (§11.2 .2). That’s most easily and most reliably done by having the lifetime of the free-store array controlled by a resource handle (e.g., string (§19.3, §36.3), vector (§13.6, §34.2), or unique_ptr (§34.3 .1)). If you allocate an array statically or on the stack, be sure never to delete[] it. Obviously, C programmers cannot follow these pieces of advice because C lacks the ability to encapsulate arrays, but that doesn’t make the advice bad in the context of C++. One of the most widely used kinds of arrays is a zero-terminated array of char. That’s the way C stores strings, so a zero-terminated array of char is often called a C-style string. C++ string liter- als follow that convention (§7.3 .2), and some standard-library functions (e.g., strcpy() and strcmp(); §43.4) rely on it. Often, a char∗ or a const char∗ is assumed to point to a zero-terminated sequence of characters. 7.3.1 Array Initializers An array can be initialized by a list of values. For example: intv1[]={1,2,3,4}; char v2[] = { 'a', 'b', 'c', 0 }; When an array is declared without a specific size, but with an initializer list, the size is calculated by counting the elements of the initializer list. Consequently, v1 and v2 are of type int[4] and char[4], respectively. If a size is explicitly specified, it is an error to give surplus elements in an ini- tializer list. For example: char v3[2] = { 'a', 'b', 0 }; // error: too many initializers char v4[3] = { 'a', 'b', 0 }; // OK If the initializer supplies too few elements for an array, 0 is used for the rest. For example: intv5[8]={1,2,3,4}; is equivalent to intv5[]={1,2,3,4 ,0,0,0,0};
ptg10564057 176 Pointers, Arrays, and References Chapter 7 There is no built-in copy operation for arrays. You cannot initialize one array with another (not even of exactly the same type), and there is no array assignment: int v6[8] = v5; // error: can’t copy an array (cannot assign an int* to an array) v6=v5; // error: no array assignment Similarly, you can’t pass arrays by value. See also §7.4 . When you need assignment to a collection of objects, use a vector (§4.4 .1, §13.6, §34.2), an array (§8.2 .4), or a valarray (§40.5) instead. An array of characters can be conveniently initialized by a string literal (§7.3 .2). 7.3.2 String Literals A string literal is a character sequence enclosed within double quotes: "this is a string" A string literal contains one more character than it appears to have; it is terminated by the null char- acter, '\0', with the value 0. For example: sizeof("Bohr")==5 The type of a string literal is ‘‘array of the appropriate number of const characters,’’ so "Bohr" is of type const char[5]. In C and in older C++ code, you could assign a string literal to a non-const char∗: void f() { char∗ p = "Plato"; // error, but accepted in pre-C++11-standard code p[4] = 'e'; // error: assignment to const } It would obviously be unsafe to accept that assignment. It was (and is) a source of subtle errors, so please don’t grumble too much if some old code fails to compile for this reason. Having string lit- erals immutable is not only obvious but also allows implementations to do significant optimizations in the way string literals are stored and accessed. If we want a string that we are guaranteed to be able to modify, we must place the characters in a non-const array: void f() { char p[] = "Zeno"; // p is an array of 5 char p[0] = 'R'; // OK } A string literal is statically allocated so that it is safe to return one from a function. For example: const char∗ error_message(int i) { // ... return "range error"; }
ptg10564057 Section 7.3 .2 String Literals 177 The memory holding "range error" will not go away after a call of error_message(). Whether two identical string literals are allocated as one array or as two is implementation- defined (§6.1). For example: const char∗ p = "Heraclitus"; const char∗ q = "Heraclitus"; void g() { if (p == q) cout << "one!\n"; // the result is implementation-defined // ... } Note that == compares addresses (pointer values) when applied to pointers, and not the values pointed to. The empty string is written as a pair of adjacent double quotes, "", and has the type const char[1]. The one character of the empty string is the terminating '\0'. The backslash convention for representing nongraphic characters (§6.2 .3 .2) can also be used within a string. This makes it possible to represent the double quote (") and the escape character backslash (\) within a string. The most common such character by far is the newline character, '\n'. For example: cout<<"beep at end of message\a\n"; The escape character, '\a', is the ASCII character BEL (also known as alert), which causes a sound to be emitted. It is not possible to have a ‘‘real’’ newline in a (nonraw) string literal: "this is not a string but a syntax error" Long strings can be broken by whitespace to make the program text neater. For example: char alpha[] = "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; The compiler will concatenate adjacent strings, so alpha could equivalently have been initialized by the single string "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; It is possible to have the null character in a string, but most programs will not suspect that there are characters after it. For example, the string "Jens\000Munk" will be treated as "Jens" by standard- library functions such as strcpy() and strlen(); see §43.4 . 7.3 .2.1 Raw Character Strings To represent a backslash (\) or a double quote (") in a string literal, we have to precede it with a backslash. That’s logical and in most cases quite simple. However, if we need a lot of backslashes and a lot of quotes in string literals, this simple technique becomes unmanageable. In particular, in regular expressions a backslash is used both as an escape character and to introduce characters
ptg10564057 178 Pointers, Arrays, and References Chapter 7 representing character classes (§37.1 .1). This is a convention shared by many programming lan- guages, so we can’t just change it. Therefore, when you write regular expressions for use with the standard regex library (Chapter 37), the fact that a backslash is an escape character becomes a notable source of errors. Consider how to write the pattern representing two words separated by a backslash (\): string s = "\\w\\\\w"; // I hope I got that right To prevent the frustration and errors caused by this clash of conventions, C++ provides raw string literals. A raw string literal is a string literal where a backslash is just a backslash (and a double quote is just a double quote) so that our example becomes: string s = R"(\w\\w)"; // I’m pretty sure I got that right Raw string literals use the R"(ccc)" notation for a sequence of characters ccc. The initial R is there to distinguish raw string literals from ordinary string literals. The parentheses are there to allow (‘‘unescaped’’) double quotes. For example: R"("quoted string")" // the string is "quoted string" So, how do we get the character sequence )" into a raw string literal? Fortunately, that’s a rare problem, but "( and )" is only the default delimiter pair. We can add delimiters before the ( and after the ) in "(...)". For example: R"∗∗∗("quoted string containing the usual terminator ("))")∗∗∗" // "quoted string containing the usual terminator ("))" The character sequence after the ) must be identical to the sequence before the (. This way we can cope with (almost) arbitrarily complicated patterns. Unless you work with regular expressions, raw string literals are probably just a curiosity (and one more thing to learn), but regular expressions are useful and widely used. Consider a real-world example: "('(?:[ˆ\\\\']|\\\\.)∗'|\"(?:[ˆ\\\\\"]|\\\\.)∗\")|" // Are the five backslashes correct or not? With examples like that, even experts easily become confused, and raw string literals provide a sig- nificant service. In contrast to nonraw string literals, a raw string literal can contain a newline. For example: string counts {R"(1 22 333)"}; is equivalent to string x {"1\n22\n333"}; 7.3 .2.2 Larger Character Sets A string with the prefix L, such as L"angst", is a string of wide characters (§6.2 .3). Its type is const wchar_t[]. Similarly, a string with the prefix LR, such as LR"(angst)", is a raw string (§7.3 .2.1) of wide characters of type const wchar_t[]. Such a string is terminated by a L'\0' character.
ptg10564057 Section 7.3 .2 .2 Larger Character Sets 179 There are six kinds of character literals supporting Unicode (Unicode literals). This sounds excessive, but there are three major encodings of Unicode: UTF-8, UTF-16, and UTF-32. For each of these three alternatives, both raw and ‘‘ordinary’’ strings are supported. All three UTF encod- ings support all Unicode characters, so which you use depends on the system you need to fit into. Essentially all Internet applications (e.g ., browsers and email) rely on one or more of these encod- ings. UTF-8 is a variable-width encoding: common characters fit into 1 byte, less frequently used characters (by some estimate of use) into 2 bytes, and rarer characters into 3 or 4 bytes. In particu- lar, the ASCII characters fit into 1 byte with the same encodings (integer values) in UTF-8 as in ASCII. The various Latin alphabets, Greek, Cyrillic, Hebrew, Arabic, and more fit into 2 bytes. A UTF-8 string is terminated by '\0', a UTF-16 string by u'\0', and a UTF-32 string by U'\0'. We can represent an ordinary English character string in a variety of ways. Consider a file name using a backslash as the separator: "folder\\file" // implementation character set string R"(folder\file)" // implementation character raw set string u8"folder\\file" // UTF-8 string u8R"(folder\file)" // UTF-8 raw string u"folder\\file" // UTF-16 string uR"(folder\file)" // UTF-16 raw string U"folder\\file" // UTF-32 string UR"(folder\file)" // UTF-32 raw string If printed, these strings will all look the same, but except for the ‘‘plain’’ and UTF-8 strings their internal representations are likely to differ. Obviously, the real purpose of Unicode strings is to be able to put Unicode characters into them. For example: u8"The official vowels in Danish are: a, e, i, o, u, \u00E6, \u00F8, \u00E5 and y." Printing that string appropriately gives you The official vowels in Danish are: a, e, i, o, u, æ, ø, å and y. The hexadecimal number after the \u is a Unicode code point (§iso.2 .14 .3) [Unicode,1996]. Such a code point is independent of the encoding used and will in fact have different representations (as bits in bytes) in different encodings. For example, u'0430' (Cyrillic lowercase letter ‘‘a’’) is the 2-byte hexadecimal value D0B0 in UTF-8, the 2-byte hexadecimal value 0403 in UTF-16, and the 4-byte hexadecimal value 00000403 in UTF-32. These hexadecimal values are referred to as univer- sal character names. The order of the us and Rs and their cases are significant: RU and Ur are not valid string prefixes. 7.4 Pointers into Arrays In C++, pointers and arrays are closely related. The name of an array can be used as a pointer to its initial element. For example:
ptg10564057 180 Pointers, Arrays, and References Chapter 7 intv[]={1,2,3,4}; int∗p1=v; // pointer to initial element (implicit conversion) int∗ p2 = &v[0]; // pointer to initial element int∗ p3 = v+4; // pointer to one-beyond-last element or graphically: p1 p2 p3 1234 v: Taking a pointer to the element one beyond the end of an array is guaranteed to work. This is important for many algorithms (§4.5, §33.1). However, since such a pointer does not in fact point to an element of the array, it may not be used for reading or writing. The result of taking the address of the element before the initial element or beyond one-past-the-last element is undefined and should be avoided. For example: int∗ p4 = v−1; // before the beginning, undefined: don’t do it int∗ p5 = v+7; // beyond the end, undefined: don’t do it The implicit conversion of an array name to a pointer to the initial element of the array is exten- sively used in function calls in C-style code. For example: extern "C" int strlen(const char∗); // from <string.h> void f() { char v[] = "Annemarie"; char∗ p=v; //implicit conversion of char[] to char* strlen(p); strlen(v); // implicit conversion of char[] to char* v=p; // error: cannot assign to array } The same value is passed to the standard-library function strlen() in both calls. The snag is that it is impossible to avoid the implicit conversion. In other words, there is no way of declaring a function so that the array v is copied when the function is called. Fortunately, there is no implicit or explicit conversion from a pointer to an array. The implicit conversion of the array argument to a pointer means that the size of the array is lost to the called function. However, the called function must somehow determine the size to perform a meaningful operation. Like other C standard-library functions taking pointers to characters, strlen() relies on zero to indicate end-of-string; strlen(p) returns the number of characters up to and not including the terminating 0. This is all pretty low-level. The standard-library vector (§4.4 .1, §13.6, §31.4), array (§8.2 .4, §34.2 .1), and string (§4.2) don’t suffer from this problem. These library types give their number of elements as their size() without having to count elements each time.
ptg10564057 Section 7.4 .1 Navigating Arrays 181 7.4.1 Navigating Arrays Efficient and elegant access to arrays (and similar data structures) is the key to many algorithms (see §4.5, Chapter 32). Access can be achieved either through a pointer to an array plus an index or through a pointer to an element. For example: void fi(char v[]) { for (int i = 0; v[i]!=0; ++i) use(v[i]); } void fp(char v[]) { for (char∗ p=v;∗p!=0; ++p) use(∗p); } The prefix ∗ operator dereferences a pointer so that ∗p is the character pointed to by p, and ++ incre- ments the pointer so that it refers to the next element of the array. There is no inherent reason why one version should be faster than the other. With modern com- pilers, identical code should be (and usually is) generated for both examples. Programmers can choose between the versions on logical and aesthetic grounds. Subscripting a built-in array is defined in terms of the pointer operations + and ∗. For every built-in array a and integer j within the range of a,wehave: a[j] == ∗(&a[0]+j) == ∗(a+j) == ∗(j+a) == j[a] It usually surprises people to find that a[j]==j[a]. For example, 3["Texas"]=="Texas"[3]=='a'. Such cleverness has no place in production code. These equivalences are pretty low-level and do not hold for standard-library containers, such as array and vector. The result of applying the arithmetic operators +, −, ++,or−− to pointers depends on the type of the object pointed to. When an arithmetic operator is applied to a pointer p of type T∗, p is assumed to point to an element of an array of objects of type T; p+1 points to the next element of that array, and p−1 points to the previous element. This implies that the integer value of p+1 will be sizeof(T) larger than the integer value of p. For example: template<typename T> int byte_diff(T∗ p, T∗ q) { return reinterpret_cast<char∗>(q)−reinterpret_cast<char∗>(p); } void diff_test() { int vi[10]; short vs[10];
ptg10564057 182 Pointers, Arrays, and References Chapter 7 cout << vi << ' ' << &vi[1] << ' ' << &vi[1]−&vi[0] << ' ' << byte_diff(&vi[0],&vi[1]) << '\n'; cout << vs << ' ' << &vs[1] << ' ' << &vs[1]−&vs[0] << ' ' << byte_diff(&vs[0],&vs[1]) << '\n'; } This produced: 0x7fffaef0 0x7fffaef4 1 4 0x7fffaedc 0x7fffaede 1 2 The pointer values were printed using the default hexadecimal notation. This shows that on my implementation, sizeof(short) is 2 and sizeof(int) is 4. Subtraction of pointers is defined only when both pointers point to elements of the same array (although the language has no fast way of ensuring that is the case). When subtracting a pointer p from another pointer q, q−p, the result is the number of array elements in the sequence [p:q) (an integer). One can add an integer to a pointer or subtract an integer from a pointer; in both cases, the result is a pointer value. If that value does not point to an element of the same array as the original pointer or one beyond, the result of using that value is undefined. For example: void f() { int v1[10]; int v2[10]; int i1 = &v1[5]−&v1[3]; // i1 = 2 int i2 = &v1[5]−&v2[3]; // result undefined int∗ p1 = v2+2; // p1 = &v2[2] int∗ p2 = v2−2; // *p2 undefined } Complicated pointer arithmetic is usually unnecessary and best avoided. Addition of pointers makes no sense and is not allowed. Arrays are not self-describing because the number of elements of an array is not guaranteed to be stored with the array. This implies that to traverse an array that does not contain a terminator the way C-style strings do, we must somehow supply the number of elements. For example: void fp(char v[], int size) { for (int i=0; i!=size; ++i) use(v[i]); // hope that v has at least size elements for(intx:v) use(x); // error: range-for does not work for pointers constintN=7; char v2[N]; for (int i=0; i!=N; ++i) use(v2[i]); for(intx:v2) use(x); // range-for works for arrays of known size }
ptg10564057 Section 7.4 .1 Navigating Arrays 183 This array concept is inherently low-level. Most advantages of the built-in array and few of the dis- advantages can be obtained through the use of the standard-library container array (§8.2 .4, §34.2 .1). Some C++ implementations offer optional range checking for arrays. However, such checking can be quite expensive, so it is often used only as a development aid (rather than being included in pro- duction code). If you are not using range checking for individual accesses, try to maintain a consis- tent policy of accessing elements only in well-defined ranges. That is best done when arrays are manipulated through the interface of a higher-level container type, such as vector, where it is harder to get confused about the range of valid elements. 7.4.2 Multidimensional Arrays Multidimensional arrays are represented as arrays of arrays; a 3-by-5 array is declared like this: int ma[3][5]; // 3 arrays with 5 ints each We can initialize ma like this: void init_ma() { for (int i = 0; i!=3; i++) for (int j = 0; j!=5; j++) ma[i][j] = 10∗i+j; } or graphically: 00 ma: 0102030410111213142021222324 The array ma is simply 15 ints that we access as if it were 3 arrays of 5 ints. In particular, there is no single object in memory that is the matrix ma – only the elements are stored. The dimensions 3 and 5 exist in the compiler source only. When we write code, it is our job to remember them some- how and supply the dimensions where needed. For example, we might print ma like this: void print_ma() { for(inti=0;i!=3;i++){ for (int j = 0; j!=5; j++) cout << ma[i][j] << '\t'; cout << '\n'; } } The comma notation used for array bounds in some languages cannot be used in C++ because the comma (,) is a sequencing operator (§10.3 .2). Fortunately, most mistakes are caught by the com- piler. For example: int bad[3,5]; // error: comma not allowed in constant expression int good[3][5]; // 3 arrays with 5 ints each int ouch = good[1,4]; // error: int initialized by int* (good[1,4] means good[4], which is an int*) int nice = good[1][4];
ptg10564057 184 Pointers, Arrays, and References Chapter 7 7.4.3 Passing Arrays Arrays cannot directly be passed by value. Instead, an array is passed as a pointer to its first ele- ment. For example: void comp(double arg[10]) // arg is a double* { for (int i=0; i!=10; ++i) arg[i]+=99; } void f() { double a1[10]; double a2[5]; double a3[100]; comp(a1); comp(a2); // disaster! comp(a3); // uses only the first 10 elements }; This code looks sane, but it is not. The code compiles, but the call comp(a2) will write beyond the bounds of a2. Also, anyone who guessed that the array was passed by value will be disappointed: the writes to arg[i] are writes directly to the elements of comp()’s argument, rather than to a copy. The function could equivalently have been written as void comp(double∗ arg) { for (int i=0; i!=10; ++i) arg[i]+=99; } Now the insanity is (hopefully) obvious. When used as a function argument, the first dimension of an array is simply treated as a pointer. Any array bound specified is simply ignored. This implies that if you want to pass a sequence of elements without losing size information, you should not pass a built-in array. Instead, you can place the array inside a class as a member (as is done for std::array) or define a class that acts as a handle (as is done for std::string and std::vector). If you insist on using arrays directly, you will have to deal with bugs and confusion without get- ting noticeable advantages in return. Consider defining a function to manipulate a two-dimensional matrix. If the dimensions are known at compile time, there is no problem: void print_m35(int m[3][5]) { for(inti=0;i!=3;i++){ for (int j = 0; j!=5; j++) cout << m[i][j] << '\t'; cout << '\n'; } }
ptg10564057 Section 7.4 .3 Passing Arrays 185 A matrix represented as a multidimensional array is passed as a pointer (rather than copied; §7.4). The first dimension of an array is irrelevant to finding the location of an element; it simply states how many elements (here, 3) of the appropriate type (here, int[5]) are present. For example, look at the layout of ma above and note that by knowing only that the second dimension is 5, we can locate ma[i][5] for any i. The first dimension can therefore be passed as an argument: void print_mi5(int m[][5], int dim1) { for (int i = 0; i!=dim1; i++) { for (int j = 0; j!=5; j++) cout << m[i][j] << '\t'; cout << '\n'; } } When both dimensions need to be passed, the ‘‘obvious solution’’ does not work: void print_mij(int m[][], int dim1, int dim2) // doesn’t behave as most people would think { for (int i = 0; i!=dim1; i++) { for (int j = 0; j!=dim2; j++) cout << m[i][j] << '\t'; // surprise! cout << '\n'; } } Fortunately, the argument declaration m[][] is illegal because the second dimension of a multidimen- sional array must be known in order to find the location of an element. However, the expression m[i][j] is (correctly) interpreted as ∗(∗(m+i)+j), although that is unlikely to be what the programmer intended. A correct solution is: void print_mij(int∗ m, int dim1, int dim2) { for (int i = 0; i!=dim1; i++) { for (int j = 0; j!=dim2; j++) cout << m[i∗dim2+j] << '\t'; // obscure cout << '\n'; } } The expression used for accessing the members in print_mij() is equivalent to the one the compiler generates when it knows the last dimension. To call this function, we pass a matrix as an ordinary pointer: int test() { int v[3][5] = { {0,1,2,3,4}, {10,11,12,13,14}, {20,21,22,23,24} };
ptg10564057 186 Pointers, Arrays, and References Chapter 7 print_m35(v); print_mi5(v,3); print_mij(&v[0][0],3,5); } Note the use of &v[0][0] for the last call; v[0] would do because it is equivalent, but v would be a type error. This kind of subtle and messy code is best hidden. If you must deal directly with multi- dimensional arrays, consider encapsulating the code relying on it. In that way, you might ease the task of the next programmer to touch the code. Providing a multidimensional array type with a proper subscripting operator saves most users from having to worry about the layout of the data in the array (§29.2 .2, §40.5 .2). The standard vector (§31.4) doesn’t suffer from these problems. 7.5 Pointers and const C++ offers two related meanings of ‘‘constant’’: • constexpr: Evaluate at compile time (§2.2 .3, §10.4). • const: Do not modify in this scope (§2.2 .3). Basically, constexpr’s role is to enable and ensure compile-time evaluation, whereas const’s pri- mary role is to specify immutability in interfaces. This section is primarily concerned with the sec- ond role: interface specification. Many objects don’t have their values changed after initialization: • Symbolic constants lead to more maintainable code than using literals directly in code. • Many pointers are often read through but never written through. • Most function parameters are read but not written to. To express this notion of immutability after initialization, we can add const to the definition of an object. For example: const int model = 90; // model is a const constintv[]={1,2,3,4}; // v[i] is a const const int x; // error: no initializer Because an object declared const cannot be assigned to, it must be initialized. Declaring something const ensures that its value will not change within its scope: void f() { model = 200; // error v[2] = 3; // error } Note that const modifies a type; it restricts the ways in which an object can be used, rather than specifying how the constant is to be allocated. For example: void g(const X∗ p) { // can’t modify *p here }
ptg10564057 Section 7.5 Pointers and const 187 void h() { Xval; //val can be modified here g(&val); // ... } When using a pointer, two objects are involved: the pointer itself and the object pointed to. ‘‘Pre- fixing’’ a declaration of a pointer with const makes the object, but not the pointer, a constant. To declare a pointer itself, rather than the object pointed to, to be a constant, we use the declarator operator ∗const instead of plain ∗. For example: void f1(char∗ p) { char s[] = "Gorm"; const char∗ pc = s; // pointer to constant pc[3] = 'g'; // error: pc points to constant pc=p; // OK char ∗const cp = s; // constant pointer cp[3] = 'a'; // OK cp=p; // error: cp is constant const char ∗const cpc = s; // const pointer to const cpc[3] = 'a'; // error: cpc points to constant cpc=p; // error: cpc is constant } The declarator operator that makes a pointer constant is ∗const. There is no const∗ declarator oper- ator, so a const appearing before the ∗ is taken to be part of the base type. For example: char ∗const cp; // const pointer to char char const∗ pc; // pointer to const char const char∗ pc2; // pointer to const char Some people find it helpful to read such declarations right-to-left, for example, ‘‘cp is a const pointer to a char’’ and ‘‘pc2 is a pointer to a char const.’’ An object that is a constant when accessed through one pointer may be variable when accessed in other ways. This is particularly useful for function arguments. By declaring a pointer argument const, the function is prohibited from modifying the object pointed to. For example: const char∗ strchr(const char∗ p, char c); // find first occurrence of c in p char∗ strchr(char∗ p, char c); // find first occurrence of c in p The first version is used for strings where the elements mustn’t be modified and returns a pointer to const that does not allow modification. The second version is used for mutable strings. You can assign the address of a non-const variable to a pointer to constant because no harm can come from that. However, the address of a constant cannot be assigned to an unrestricted pointer because this would allow the object’s value to be changed. For example:
ptg10564057 188 Pointers, Arrays, and References Chapter 7 void f4() { inta=1; constintc=2; const int∗ p1 = &c; // OK const int∗ p2 = &a; // OK int∗ p3 = &c; // error: initialization of int* with const int* ∗p3=7; // try to change the value of c } It is possible, but typically unwise, to explicitly remove the restrictions on a pointer to const by explicit type conversion (§16.2.9, §11.5). 7.6 Pointers and Ownership A resource is something that has to be acquired and later released (§5.2). Memory acquired by new and released by delete (§11.2) and files opened by fopen() and closed by fclose() (§43.2) are exam- ples of resources where the most direct handle to the resource is a pointer. This can be most con- fusing because a pointer is easily passed around in a program, and there is nothing in the type sys- tem that distinguishes a pointer that owns a resource from one that does not. Consider: void confused(int∗ p) { // delete p? } int global {7}; void f() { X∗ pn = new int{7}; int i {7}; intq=&i; confused(pn); confused(q); confused(&global); } If confused() deletes p the program will seriously misbehave for the second two calls because we may not delete objects not allocated by new (§11.2). If confused() does not delete p the program leaks (§11.2 .1). In this case, obviously f() must manage the lifetime of the object it creates on the free store, but in general keeping track of what needs to be deleted in a large program requires a simple and consistent strategy. It is usually a good idea to immediately place a pointer that represents ownership in a resource handle class, such as vector, string, and unique_ptr. That way, we can assume that every pointer that is not within a resource handle is not an owner and must not be deleted. Chapter 13 discusses resource management in greater detail.
ptg10564057 Section 7.7 References 189 7.7 References A pointer allows us to pass potentially large amounts of data around at low cost: instead of copying the data we simply pass its address as a pointer value. The type of the pointer determines what can be done to the data through the pointer. Using a pointer differs from using the name of an object in a few ways: • We use a different syntax, for example, ∗p instead of obj and p−>m rather than obj.m. • We can make a pointer point to different objects at different times. • We must be more careful when using pointers than when using an object directly: a pointer may be a nullptr or point to an object that wasn’t the one we expected. These differences can be annoying; for example, some programmers find f(&x) ugly compared to f(x). Worse, managing pointer variables with varying values and protecting code against the possi- bility of nullptr can be a significant burden. Finally, when we want to overload an operator, say +, we want to write x+y rather than &x+&y. The language mechanism addressing these problems is called a reference. Like a pointer, a reference is an alias for an object, is usually implemented to hold a machine address of an object, and does not impose performance overhead compared to pointers, but it differs from a pointer in that: • You access a reference with exactly the same syntax as the name of an object. • A reference always refers to the object to which it was initialized. • There is no ‘‘null reference,’’ and we may assume that a reference refers to an object (§7.7 .4). A reference is an alternative name for an object, an alias. The main use of references is for specify- ing arguments and return values for functions in general and for overloaded operators (Chapter 18) in particular. For example: template<class T> class vector { T∗ elem; // ... public: T& operator[](int i) { return elem[i]; } // return reference to element const T& operator[](int i) const { return elem[i]; } // return reference to const element void push_back(const T& a); // pass element to be added by reference // ... }; void f(const vector<double>& v) { double d1 = v[1]; // copy the value of the double referred to by v.operator[](1) into d1 v[2] = 7; // place 7 in the double referred to by the result of v.operator[](2) v.push_back(d1); // give push_back() a reference to d1 to work with } The idea of passing function arguments by reference is as old as high-level programming languages (the first version of Fortran used that).
ptg10564057 190 Pointers, Arrays, and References Chapter 7 To reflect the lvalue/rvalue and const/non-const distinctions, there are three kinds of references: • lvalue references: to refer to objects whose value we want to change • const references: to refer to objects whose value we do not want to change (e.g ., a constant) • rvalue references: to refer to objects whose value we do not need to preserve after we have used it (e.g ., a temporary) Collectively, they are called references. The first two are both called lvalue references. 7.7.1 Lvalue References In a type name, the notation X& means ‘‘reference to X.’’ It is used for references to lvalues, so it is often called an lvalue reference. For example: void f() { intvar=1; int& r {var}; // r and var now refer to the same int intx=r; // x becomes 1 r=2; //var becomes 2 } To ensure that a reference is a name for something (that is, that it is bound to an object), we must initialize the reference. For example: intvar=1; int& r1 {var}; // OK: r1 initialized int& r2; // error: initializer missing extern int& r3; // OK: r3 initialized elsewhere Initialization of a reference is something quite different from assignment to it. Despite appear- ances, no operator operates on a reference. For example: void g() { intvar=0; int& rr {var}; ++rr; // var is incremented to 1 int∗ pp = &rr; // pp points to var } Here, ++rr does not increment the reference rr; rather, ++ is applied to the int to which rr refers, that is, to var. Consequently, the value of a reference cannot be changed after initialization; it always refers to the object it was initialized to denote. To get a pointer to the object denoted by a reference rr, we can write &rr. Thus, we cannot have a pointer to a reference. Furthermore, we cannot define an array of references. In that sense, a reference is not an object. The obvious implementation of a reference is as a (constant) pointer that is dereferenced each time it is used. It doesn’t do much harm to think about references that way, as long as one remem- bers that a reference isn’t an object that can be manipulated the way a pointer is:
ptg10564057 Section 7.7 .1 Lvalue References 191 1 ii: &ii pp: rr: In some cases, the compiler can optimize away a reference so that there is no object representing that reference at run time. Initialization of a reference is trivial when the initializer is an lvalue (an object whose address you can take; see §6.4). The initializer for a ‘‘plain’’ T& must be an lvalue of type T. The initializer for a const T& need not be an lvalue or even of type T. In such cases: [1] First, implicit type conversion to T is applied if necessary (see §10.5). [2] Then, the resulting value is placed in a temporary variable of type T. [3] Finally, this temporary variable is used as the value of the initializer. Consider: double& dr = 1; // error: lvalue needed const double& cdr {1}; // OK The interpretation of this last initialization might be: double temp = double{1}; // first create a temporary with the right value const double& cdr {temp}; // then use the temporary as the initializer for cdr A temporary created to hold a reference initializer persists until the end of its reference’s scope. References to variables and references to constants are distinguished because introducing a tem- porary for a variable would have been highly error-prone; an assignment to the variable would become an assignment to the – soon -to-disappear – temporary. No such problem exists for refer- ences to constants, and references to constants are often important as function arguments (§18.2 .4). A reference can be used to specify a function argument so that the function can change the value of an object passed to it. For example: void increment(int& aa) { ++aa; } void f() { intx=1; increment(x); // x=2 } The semantics of argument passing are defined to be those of initialization, so when called, incre- ment’s argument aa became another name for x. To keep a program readable, it is often best to avoid functions that modify their arguments. Instead, you can return a value from the function explicitly:
ptg10564057 192 Pointers, Arrays, and References Chapter 7 int next(int p) { return p+1; } void g() { intx=1; increment(x); // x=2 x = next(x); // x=3 } The increment(x) notation doesn’t give a clue to the reader that x’s value is being modified, the way x=next(x) does. Consequently, ‘‘plain’’ reference arguments should be used only where the name of the function gives a strong hint that the reference argument is modified. References can also be used as return types. This is mostly used to define functions that can be used on both the left-hand and right-hand sides of an assignment. A Map is a good example. For example: template<class K, class V> class Map { // a simple map class public: V& operator[](const K& v); // return the value corresponding to the key v pair<K,V>∗ begin() { return &elem[0]; } pair<K,V>∗ end() { return &elem[0]+elem.size(); } private: vector<pair<K,V>> elem; // {key,value} pairs }; The standard-library map (§4.4 .3, §31.4 .3) is typically implemented as a red-black tree, but to avoid distracting implementation details, I’ll just show an implementation based on linear search for a key match: template<class K, class V> V& Map<K,V>::operator[](const K& k) { for (auto& x : elem) if (k == x.first) return x.second; elem.push_back({k,V{}}); // add pair at end (§4.4.2) return elem.back().second; // return the (default) value of the new element } I pass the key argument, k, by reference because it might be of a type that is expensive to copy. Similarly, I return the value by reference because it too might be of a type that is expensive to copy. I use a const reference for k because I don’t want to modify it and because I might want to use a lit- eral or a temporary object as an argument. I return the result by non-const reference because the user of a Map might very well want to modify the found value. For example:
ptg10564057 Section 7.7 .1 Lvalue References 193 int main() // count the number of occurrences of each word on input { Map<string,int> buf; for (string s; cin>>s;) ++buf[s]; for (const auto& x : buf) cout << x.first << ": " << x.second << '\n'; } Each time around, the input loop reads one word from the standard input stream cin into the string s (§4.3 .2) and then updates the counter associated with it. Finally, the resulting table of different words in the input, each with its number of occurrences, is printed. For example, given the input aabbbbaaaabbaaaa this program will produce aa: 5 bb: 3 The range- for loop works for this because Map defined begin() and end(), just as is done for the standard-library map. 7.7.2 Rvalue References The basic idea of having more than one kind of reference is to support different uses of objects: • A non-const lvalue reference refers to an object, to which the user of the reference can write. •A const lvalue reference refers to a constant, which is immutable from the point of view of the user of the reference. • An rvalue reference refers to a temporary object, which the user of the reference can (and typically will) modify, assuming that the object will never be used again. We want to know if a reference refers to a temporary, because if it does, we can sometimes turn an expensive copy operation into a cheap move operation (§3.3.2, §17.1, §17.5.2). An object (such as a string or a list) that is represented by a small descriptor pointing to a potentially huge amount of information can be simply and cheaply moved if we know that the source isn’t going to be used again. The classic example is a return value where the compiler knows that a local variable returned will never again be used (§3.3.2). An rvalue reference can bind to an rvalue, but not to an lvalue. In that, an rvalue reference is exactly opposite to an lvalue reference. For example: string var {"Cambridge"}; string f(); string& r1 {var}; // lvalue reference, bind r1 to var (an lvalue) string& r2 {f()}; // lvalue reference, error: f() is an rvalue string& r3 {"Princeton"}; // lvalue reference, error: cannot bind to temporary
ptg10564057 194 Pointers, Arrays, and References Chapter 7 string&& rr1 {f()}; // rvalue reference, fine: bind rr1 to rvalue (a temporary) string&& rr2 {var}; // rvalue reference, error: var is an lvalue string&& rr3 {"Oxford"}; // rr3 refers to a temporary holding "Oxford" const string cr1& {"Harvard"}; // OK: make temporary and bind to cr1 The && declarator operator means ‘‘rvalue reference.’’ We do not use const rvalue references; most of the benefits from using rvalue references involve writing to the object to which it refers. Both a const lvalue reference and an rvalue reference can bind to an rvalue. However, the purposes will be fundamentally different: • We use rvalue references to implement a ‘‘destructive read’’ for optimization of what would otherwise have required a copy. • We use a const lvalue reference to prevent modification of an argument. An object referred to by an rvalue reference is accessed exactly like an object referred to by an lvalue reference or an ordinary variable name. For example: string f(string&& s) { if (s.size()) s[0] = toupper(s[0]); return s; } Sometimes, a programmer knows that an object won’t be used again, even though the compiler does not. Consider: template<class T> swap(T& a, T& b) // "old-style swap" { T tmp {a}; // now we have two copies of a a=b; //nowwehavetwocopiesofb b = tmp; // now we have two copies of tmp (aka a) } If T is a type for which it can be expensive to copy elements, such as string and vector, this swap() becomes an expensive operation. Note something curious: we didn’t want any copies at all; we just wanted to move the values of a, b, and tmp around. We can tell that to the compiler: template<class T> void swap(T& a, T& b) // "perfect swap" (almost) { T tmp {static_cast<T&&>(a)}; // the initialization may write to a a = static_cast<T&&>(b); // the assignment may write to b b = static_cast<T&&>(tmp); // the assignment may write to tmp } The result value of static_cast<T&&>(x) is an rvalue of type T&& for x. An operation that is opti- mized for rvalues can now use its optimization for x. In particular, if a type T has a move construc- tor (§3.3 .2, §17.5 .2) or a move assignment, it will be used. Consider vector:
ptg10564057 Section 7.7 .2 Rvalue References 195 template<class T> class vector { // ... vector(const vector& r); // copy constructor (copy r’s representation) vector(vector&& r); // move constructor ("steal" representation from r) }; vector<string> s; vector<string> s2 {s}; // s is an lvalue, so use copy constructor vector<string> s3 {s+"tail"); // s+"tail" is an rvalue so pick move constructor The use of static_cast in swap() is a bit verbose and slightly prone to mistyping, so the standard library provides a move() function: move(x) means static_cast<X&&>(x) where X is the type of x. Given that, we can clean up the definition of swap() a bit: template<class T> void swap(T& a, T& b) // "perfect swap" (almost) { T tmp {move(a)}; // move from a a = move(b); // move from b b = move(tmp); // move from tmp } In contrast to the original swap(), this latest version need not make any copies; it will use move operations whenever possible. Since move(x) does not move x (it simply produces an rvalue reference to x), it would have been better if move() had been called rval(), but by now move() has been used for years. I deemed this swap() ‘‘almost perfect’’ because it will swap only lvalues. Consider: void f(vector<int>& v) { swap(v,vector<int>{1,2,3}); // replace v’s elements with 1,2,3 // ... } It is not uncommon to want to replace the contents of a container with some sort of default value, but this particular swap() cannot do that. A solution is to augment it by two overloads: template<class T> void swap(T&& a, T& b); template<class T> void swap(T& a, T&& b) Our example will be handled by that last version of swap(). The standard library takes a different approach by defining shrink_to_fit() and clear() for vector, string, etc. (§31.3 .3) to handle the most common cases of rvalue arguments to swap(): void f(string& s, vector<int>& v) { s.shrink_to_fit(); // make s.capacity()==s.size() swap(s,string{s}); // make s.capacity()==s.size()
ptg10564057 196 Pointers, Arrays, and References Chapter 7 v.clear(); // make v empty swap(v.vector<int>{}); // make v empty v={}; // make v empty } Rvalue references can also be used to provide perfect forwarding (§23.5 .2 .1, §35.5 .1). All standard-library containers provide move constructors and move assignment (§31.3 .2). Also, their operations that insert new elements, such as insert() and push_back(), have versions that take rvalue references. 7.7.3 References to References It you take a reference to a reference to a type, you get a reference to that type, rather than some kind of special reference to reference type. But what kind of reference? Lvalue reference or rvalue reference? Consider: using rr_i = int&&; using lr_i = int&; using rr_rr _i = rr_i&&; // ‘‘int && &&’’ is an int&& using lr_rr _i = rr_i&; // ‘‘int && &’’ is an int& using rr_lr_i = lr_i&&; // ‘‘int & &&’’ is an int& using lr_lr_i = lr_i&; // ‘‘int & &’’ is an int& In other words, lvalue reference always wins. This makes sense: nothing we can do with types can change the fact that an lvalue reference refers to an lvalue. This is sometimes known as reference collapse. The syntax does not allow int&&&r=i; Reference to reference can only happen as the result of an alias (§3.4 .5, §6.5) or a template type argument (§23.5.2 .1). 7.7.4 Pointers and References Pointers and references are two mechanisms for referring to an object from different places in a program without copying. We can show this similarity graphically: 1 ii: &ii pp: rr: Each has its strengths and weaknesses. If you need to change which object to refer to, use a pointer. You can use =, +=, −=, ++, and −− to change the value of a pointer variable (§11.1 .4). For example:
ptg10564057 Section 7.7 .4 Pointers and References 197 void fp(char∗ p) { while (∗p) cout << ++∗p; } void fr(char& r) { while (r) cout << ++r; // oops: increments the char referred to, not the reference // near-infinite loop! } void fr2(char& r) { char∗ p = &r; // get a pointer to the object referred to while (∗p) cout << ++∗p; } Conversely, if you want to be sure that a name always refers to the same object, use a reference. For example: template<class T> class Proxy { // Proxy refers to the object with which it is initialized T& m; public: Proxy(T& mm) :m{mm} {} // ... }; template<class T> class Handle { // Handle refers to its current object T∗ m; public: Proxy(T∗ mm) :m{mm} {} void rebind(T∗ mm) { m = mm; } // ... }; If you want to use a user-defined (overloaded) operator (§18.1) on something that refers to an object, use a reference: Matrix operator+(const Matrix&, const Matrix&); // OK Matrix operator−(const Matrix∗, const Matrix∗); // error: no user-defined type argument Matrix y, z; // ... Matrix x = y+z; // OK Matrix x2 = &y−&z; // error and ugly It is not possible to (re)define an operator for a pair of built-in types, such as pointers (§18.2 .3).
ptg10564057 198 Pointers, Arrays, and References Chapter 7 If you want a collection of something that refers to an object, you must use a pointer: int x, y; string& a1[] = {x, y}; // error: array of references string∗ a2[] = {&x, &y}; // OK vector<string&> s1 = {x , y}; // error: vector of references vector<string∗> s2 = {&x, &y}; // OK Once we leave the cases where C++ leaves no choice for the programmer, we enter the domain of aesthetics. Ideally, we will make our choices so as to minimize the probability of error and in par- ticular to maximize readability of code. If you need a notion of ‘‘no value,’’ pointers offer nullptr. There is no equivalent ‘‘null refer- ence,’’ so if you need a ‘‘no value,’’ using a pointer may be most appropriate. For example: void fp(X∗ p) { if (p == nullptr) { // no value } else { // use *p } } void fr(X& r) // common style { // assume that r is valid and use it } If you really want to, you can construct and check for a ‘‘null reference’’ for a particular type: void fr2(X& r) { if (&r == &nullX) { // or maybe r==nullX // no value } else { //user } } Obviously, you need to have suitably defined nullX. The style is not idiomatic and I don’t recom- mend it. A programmer is allowed to assume that a reference is valid. It is possible to create an invalid reference, but you have to go out of your way to do so. For example: char∗ ident(char ∗ p) { return p; } char& r {∗ident(nullptr)}; // invalid code This code is not valid C++ code. Don’t write such code even if your current implementation doesn’t catch it.
ptg10564057 Section 7.8 Advice 199 7.8 Advice [1] Keep use of pointers simple and straightforward; §7.4 .1 . [2] Avoid nontrivial pointer arithmetic; §7.4. [3] Take care not to write beyond the bounds of an array; §7.4 .1. [4] Avoid multidimensional arrays; define suitable containers instead; §7.4.2 . [5] Use nullptr rather than 0 or NULL; §7.2 .2 . [6] Use containers (e.g., vector, array, and valarray) rather than built-in (C-style) arrays; §7.4 .1 . [7] Use string rather than zero-terminated arrays of char; §7.4. [8] Use raw strings for string literals with complicated uses of backslash; §7.3 .2 .1. [9] Prefer const reference arguments to plain reference arguments; §7.7 .3 . [10] Use rvalue references (only) for forwarding and move semantics; §7.7 .2. [11] Keep pointers that represent ownership inside handle classes; §7.6 . [12] Avoid void∗ except in low-level code; §7.2 .1 . [13] Use const pointers and const references to express immutability in interfaces; §7.5 . [14] Prefer references to pointers as arguments, except where ‘‘no object’’ is a reasonable option; §7.7 .4 .
ptg10564057 This page intentionally left blank
ptg10564057 8 Structures, Unions, and Enumerations Form a more perfect Union. – The people • Introduction • Structures struct Layout; struct Names; Structures and Classes; Structures and Arrays; Type Equiv- alence; Plain Old Data; Fields • Unions Unions and Classes; Anonymous unions • Enumerations enum classes; Plain enums; Unnamed enums • Advice 8.1 Introduction The key to effective use of C++ is the definition and use of user-defined types. This chapter intro- duces the three most primitive variants of the notion of a user-defined type: •A struct (a structure) is a sequence of elements (called members) of arbitrary types. •A union is a struct that holds the value of just one of its elements at any one time. •A n enum (an enumeration) is a type with a set of named constants (called enumerators). • enum class (a scoped enumeration) is an enum where the enumerators are within the scope of the enumeration and no implicit conversions to other types are provided. Variants of these kinds of simple types have existed since the earliest days of C++. They are pri- marily focused on the representation of data and are the backbone of most C-style programming. The notion of a struct as described here is a simple form of a class (§3.2, Chapter 16).
ptg10564057 202 Structures, Unions, and Enumerations Chapter 8 8.2 Structures An array is an aggregate of elements of the same type. In its simplest form, a struct is an aggregate of elements of arbitrary types. For example: struct Address { const char∗ name; // "Jim Dandy" int number; // 61 const char∗ street; // "South St" const char∗ town; // "New Providence" char state[2]; // 'N' 'J' const char∗ zip; // "07974" }; This defines a type called Address consisting of the items you need in order to send mail to some- one within the USA. Note the terminating semicolon. Variables of type Address can be declared exactly like other variables, and the individual mem- bers can be accessed using the . (dot) operator. For example: void f() { Address jd; jd.name = "Jim Dandy"; jd.number = 61; } Variables of struct types can be initialized using the {} notation (§6.3 .5). For example: Address jd = { "Jim Dandy", 61, "South St", "New Providence", {'N','J'}, "07974" }; Note that jd.state could not be initialized by the string "NJ". Strings are terminated by a zero char- acter, '\0',so"NJ" has three characters – one more than will fit into jd.state. I deliberately use rather low-level types for the members to illustrate how that can be done and what kinds of problems it can cause. Structures are often accessed through pointers using the −> (struct pointer dereference) operator. For example: void print_addr(Address∗ p) { cout << p−>name << '\n' << p−>number << ' ' << p−>street << '\n' << p−>town << '\n' << p−>state[0] << p−>state[1] << ' ' << p−>zip << '\n'; } When p is a pointer, p−>m is equivalent to (∗p).m.
ptg10564057 Section 8.2 Structures 203 Alternatively, a struct can be passed by reference and accessed using the . (struct member access) operator: void print_addr2(const Address& r) { cout << r.name << '\n' << r.number << ' ' << r.street << '\n' << r.town << '\n' << r.state[0] << r.state[1] << ' ' << r.zip << '\n'; } Argument passing is discussed in §12.2 . Objects of structure types can be assigned, passed as function arguments, and returned as the result from a function. For example: Address current; Address set_current(Address next) { address prev = current; current = next; return prev; } Other plausible operations, such as comparison (== and !=), are not available by default. However, the user can define such operators (§3.2 .1 .1, Chapter 18). 8.2.1 struct Layout An object of a struct holds its members in the order they are declared. For example, we might store primitive equipment readout in a structure like this: struct Readout { char hour; // [0:23] int value; char seq; // sequence mark ['a':'z'] }; You could imagine the members of a Readout object laid out in memory like this: hour: value: seq: Members are allocated in memory in declaration order, so the address of hour must be less than the address of value. See also §8.2 .6. However, the size of an object of a struct is not necessarily the sum of the sizes of its members. This is because many machines require objects of certain types to be allocated on architecture- dependent boundaries or handle such objects much more efficiently if they are. For example, inte- gers are often allocated on word boundaries. On such machines, objects are said to have to be properly aligned (§6.2 .9). This leads to ‘‘holes’’ in the structures. A more realistic layout of a
ptg10564057 204 Structures, Unions, and Enumerations Chapter 8 Readout on a machine with 4-byte int would be: hour: value: seq: In this case, as on many machines, sizeof(Readout) is 12, and not 6 as one would naively expect from simply adding the sizes of the individual members. You can minimize wasted space by simply ordering members by size (largest member first). For example: struct Readout { int value; char hour; // [0:23] char seq; // sequence mark ['a':'z'] }; This would give us: value: (hour,seq): Note that this still leaves a 2-byte ‘‘hole’’ (unused space) in a Readout and sizeof(Readout)==8. The reason is that we need to maintain alignment when we put two objects next to each other, say, in an array of Readouts. The size of an array of 10 Readout objects is 10∗sizeof(Readout). It is usually best to order members for readability and sort them by size only if there is a demonstrated need to optimize. Use of multiple access specifiers (i.e., public, private,orprotected) can affect layout (§20.5). 8.2.2 struct Names The name of a type becomes available for use immediately after it has been encountered and not just after the complete declaration has been seen. For example: struct Link { Link∗ previous; Link∗ successor; }; However, it is not possible to declare new objects of a struct until its complete declaration has been seen. For example: struct No_good { No_good member; // error: recursive definition }; This is an error because the compiler is not able to determine the size of No_good. To allow two (or
ptg10564057 Section 8.2 .2 struct Names 205 more) structs to refer to each other, we can declare a name to be the name of a struct. For example: struct List; // struct name declaration: List to be defined later struct Link { Link∗ pre; Link∗ suc; List∗ member_of; int data; }; struct List { Link∗ head; }; Without the first declaration of List, use of the pointer type List∗ in the declaration of Link would have been a syntax error. The name of a struct can be used before the type is defined as long as that use does not require the name of a member or the size of the structure to be known. However, until the completion of the declaration of a struct, that struct is an incomplete type. For example: struct S; // ‘‘S’’ is the name of some type extern S a; S f(); void g(S); S∗ h(S∗); However, many such declarations cannot be used unless the type S is defined: void k(S∗ p) { Sa; //error: S not defined; size needed to allocate f(); // error: S not defined; size needed to return value g(a); // error: S not defined; size needed to pass argument p−>m = 7; // error: S not defined; member name not known S∗ q = h(p); // ok: pointers can be allocated and passed q−>m = 7; // error: S not defined; member name not known } For reasons that reach into the prehistory of C, it is possible to declare a struct and a non-struct with the same name in the same scope. For example: struct stat { /* ... */ }; int stat(char∗ name, struct stat∗ buf); In that case, the plain name (stat) is the name of the non-struct, and the struct must be referred to with the prefix struct. Similarly, the keywords class, union (§8.3), and enum (§8.4) can be used as prefixes for disambiguation. However, it is best not to overload names to make such explicit disam- biguation necessary.
ptg10564057 206 Structures, Unions, and Enumerations Chapter 8 8.2.3 Structures and Classes A struct is simply a class where the members are public by default. So, a struct can have member functions (§2.3 .2, Chapter 16). In particular, a struct can have constructors. For example: struct Points { vector<Point> elem; // must contain at least one Point Points(Point p0) { elem.push_back(p0);} Points(Point p0, Point p1) { elem.push_back(p0); elem.push_back(p1); } // ... }; Points x0; // error: no default constructor Points x1{ {100,200} }; // one Point Points x1{ {100,200}, {300,400} }; // two Points You do not need to define a constructor simply to initialize members in order. For example: struct Point { int x, y; }; Point p0; // danger: uninitialized if in local scope (§6.3 .5 .1) Point p1 {}; // default construction: {{},{}}; that is {0.0} Point p2 {1}; // the second member is default constructed: {1,{}}; that is {1,0} Point p3 {1,2}; // {1,2} Constructors are needed if you need to reorder arguments, validate arguments, modify arguments, establish invariants (§2.4 .3 .2, §13.4), etc. For example: struct Address { string name; // "Jim Dandy" int number; // 61 string street; // "South St" string town; // "New Providence" char state[2]; // ’N’ ’J’ char zip[5]; // 07974 Address(const string n, int nu, const string& s, const string& t, const string& st, int z); }; Here, I added a constructor to ensure that every member was initialized and to allow me to use a string and an int for the postal code, rather than fiddling with individual characters. For example: Address jd = { "Jim Dandy", 61, "South St", "New Providence", "NJ", 7974 // (07974 would be octal; §6.2 .4 .1) }; The Address constructor might be defined like this:
ptg10564057 Section 8.2 .3 Structures and Classes 207 Address::Address(const string& n, int nu, const string& s, const string& t, const string& st, int z) // validate postal code :name{n}, number{nu}, street{s}, town{t} { if (st.size()!=2) error("State abbreviation should be two characters") state = {st[0],st[1]}; // store postal code as characters ostringstream ost; // an output string stream; see §38.4 .2 ost << z; // extract characters from int string zi {ost.str()}; switch (zi.size()) { case 5: zip = {zi[0], zi[1], zi[2], zi[3], zi[4]}; break; case 4: // starts with ’0’ zip = {'0', zi[0], zi[1], zi[2], zi[3]}; break; default: error("unexpected ZIP code format"); } // ... check that the code makes sense ... } 8.2.4 Structures and Arrays Naturally, we can have arrays of structs and structs containing arrays. For example: struct Point { int x,y }; Point points[3] {{1,2},{3,4},{5,6}}; int x2 = points[2].x; struct Array { Point elem[3]; }; Array points2 {{1,2},{3,4},{5,6}}; int y2 = points2.elem[2].y; Placing a built-in array in a struct allows us to treat that array as an object: we can copy the struct containing it in initialization (including argument passing and function return) and assignment. For example:
ptg10564057 208 Structures, Unions, and Enumerations Chapter 8 Array shift(Array a, Point p) { for (int i=0; i!=3; ++i) { a.elem[i].x += p.x; a.elem[i].y += p.y; } return a; } Array ax = shift(points2,{10,20}); The notation for Array is a bit primitive: Why i!=3? Why keep repeating .elem[i]? Why just ele- ments of type Point? The standard library provides std::array (§34.2 .1) as a more complete and ele- gant development of the idea of a fixed-size array as a struct: template<typename T, size_t N > struct array { // simplified (see §34.2.1) T elem[N]; T∗ begin() noexcept { return elem; } const T∗ begin() const noexcept {return elem; } T∗ end() noexcept { return elem+N; } const T∗ end() const noexcept { return elem+N; } constexpr size_t size() noexcept; T& operator[](size_t n) { return elem[n]; } const T& operator[](size_type n) const { return elem[n]; } T ∗ data() noexcept { return elem; } const T ∗ data() const noexcept { return elem; } // ... }; This array is a template to allow arbitrary numbers of elements of arbitrary types. It also deals directly with the possibility of exceptions (§13.5 .1 .1) and const objects (§16.2 .9 .1). Using array, we can now write: struct Point { int x,y }; using Array = array<Point,3>; // array of 3 Points Array points {{1,2},{3,4},{5,6}}; int x2 = points[2].x; int y2 = points[2].y;
ptg10564057 Section 8.2 .4 Structures and Arrays 209 Array shift(Array a, Point p) { for (int i=0; i!=a.size(); ++i) { a[i].x += p.x; a[i].y += p.y; } return a; } Array ax = shift(points,{10,20}); The main advantages of std::array over a built-in array are that it is a proper object type (has assign- ment, etc.) and does not implicitly convert to a pointer to an individual element: ostream& operator<<(ostream& os, Point p) { cout << '{' << p[i].x << ',' << p[i].y << '}'; } void print(Point a[],int s) // must specify number of elements { for (int i=0; i!=s; ++i) cout << a[i] << '\n'; } template<typename T, int N> void print(array<T,N>& a) { for (int i=0; i!=a.size(); ++i) cout << a[i] << '\n'; } Point point1[] = {{1,2},{3,4},{5,6}}; // 3 elements array<Point,3> point2 = {{1,2},{3,4},{5,6}}; // 3 elements void f() { print(point1,4); //4isabaderror print(point2); } The disadvantage of std::array compared to a built-in array is that we can’t deduce the number of elements from the length of the initializer: Point point1[] = {{1,2},{3,4},{5,6}}; // 3 elements array<Point,3> point2 = {{1,2},{3,4},{5,6}}; // 3 elements array<Point> point3 = {{1,2},{3,4},{5,6}}; // error: number of elements not given
ptg10564057 210 Structures, Unions, and Enumerations Chapter 8 8.2.5 Type Equivalence Tw o structs are different types even when they have the same members. For example: struct S1 { int a; }; struct S2 { int a; }; S1 and S2 are two different types, so: S1 x; S2 y = x; // error: type mismatch A struct is also a different type from a type used as a member. For example: S1 x; int i = x; // error: type mismatch Every struct must have a unique definition in a program (§15.2 .3). 8.2.6 Plain Old Data Sometimes, we want to treat an object as just ‘‘plain old data’’ (a contiguous sequence of bytes in memory) and not worry about more advanced semantic notions, such as run-time polymorphism (§3.2 .3, §20.3 .2), user-defined copy semantics (§3.3, §17.5), etc. Often, the reason for doing so is to be able to move objects around in the most efficient way the hardware is capable of. For exam- ple, copying a 100-element array using 100 calls of a copy constructor is unlikely to be as fast as calling std::memcpy(), which typically simply uses a block-move machine instruction. Even if the constructor is inlined, it could be hard for an optimizer to discover this optimization. Such ‘‘tricks’’ are not uncommon, and are important, in implementations of containers, such as vector, and in low- level I/O routines. They are unnecessary and should be avoided in higher-level code. So, a POD (‘‘Plain Old Data’’) is an object that can be manipulated as ‘‘just data’’ without wor- rying about complications of class layouts or user-defined semantics for construction, copy, and move. For example: struct S0 { }; //aPOD struct S1 { int a; }; //aPOD structS2{inta;S2(intaa):a(aa){}}; // not a POD (no default constructor) structS3{inta;S3(intaa):a(aa){}S3(){}}; // a POD (user-defined default constructor) struct S4 { int a; S4(int aa) : a(aa) { } S4() = default; }; // a POD struct S5 { virtual void f(); /* ... */ }; // not a POD (has a virtual function) structS6:S1{}; //aPOD structS7:S0{intb;}; //aPOD structS8:S1{intb;}; // not a POD (data in both S1 and S8) struct S9 : S0, S1 {}; //aPOD For us to manipulate an object as ‘‘just data’’ (as a POD), the object must • not have a complicated layout (e.g ., with a vptr; (§3.2 .3, §20.3 .2), • not have nonstandard (user-defined) copy semantics, and • have a trivial default constructor. Obviously, we need to be precise about the definition of POD so that we only use such
ptg10564057 Section 8.2 .6 Plain Old Data 211 optimizations where they don’t break any language guarantees. Formally (§iso.3 .9, §iso.9), a POD object must be of •a standard layout type, and •a trivially copyable type, • a type with a trivial default constructor. A related concept is a trivial type, which is a type with • a trivial default constructor and • trivial copy and move operations Informally, a default constructor is trivial if it does not need to do any work (use =default if you need to define one §17.6 .1). A type has standard layout unless it • has a non-static member or a base that is not standard layout, • has a virtual function (§3.2 .3, §20.3 .2), • has a virtual base (§21.3 .5), • has a member that is a reference (§7.7), • has multiple access specifiers for non-static data members (§20.5), or • prevents important layout optimizations • by having non-static data members in more than one base class or in both the derived class and a base, or • by having a base class of the same type as the first non-static data member. Basically, a standard layout type is one that has a layout with an obvious equivalent in C and is in the union of what common C++ Application Binary Interfaces (ABIs) can handle. A type is trivially copyable unless it has a nontrivial copy operation, move operation, or de- structor (§3.2 .1 .2, §17.6). Informally, a copy operation is trivial if it can be implemented as a bit- wise copy. So, what makes a copy, move, or destructor nontrivial? • It is user-defined. • Its class has a virtual function. • Its class has a virtual base. • Its class has a base or a member that is not trivial. An object of built-in type is trivially copyable, and has standard layout. Also, an array of trivially copyable objects is trivially copyable and an array of standard layout objects has standard layout. Consider an example: template<typename T> void mycopy(T∗ to, const T∗ from, int count); I’d like to optimize the simple case where T is a POD. I could do that by only calling mycopy() for PODs, but that’s error-prone: if I use mycopy() can I rely on a maintainer of the code to remember never to call mycopy() for non-PODs? Realistically, I cannot. Alternatively, I could call std::copy(), which is most likely implemented with the necessary optimization. Anyway, here is the general and optimized code:
ptg10564057 212 Structures, Unions, and Enumerations Chapter 8 template<typename T> void mycopy(T∗ to, const T∗ from, int count) { if (is_pod<T>::value) memcpy(to,from,count∗sizeof(T)); else for (int i=0; i!=count; ++i) to[i]=from[i]; } The is_pod is a standard-library type property predicate (§35.4 .1) defined in <type_traits> allowing us to ask the question ‘‘Is T a POD?’’ in our code. The best thing about is_pod<T> is that it saves us from remembering the exact rules for what a POD is. Note that adding or subtracting non-default constructors does not affect layout or performance (that was not true in C++98). If you feel an urge to become a language lawyer, study the layout and triviality concepts in the standard (§iso.3 .9, §iso.9) and try to think about their implications to programmers and compiler writers. Doing so might cure you of the urge before it has consumed too much of your time. 8.2.7 Fields It seems extravagant to use a whole byte (a char or a bool) to represent a binary variable – for exam- ple, an on/off switch – but a char is the smallest object that can be independently allocated and addressed in C++ (§7.2). It is possible, however, to bundle several such tiny variables together as fields in a struct. A field is often called a bit-field. A member is defined to be a field by specifying the number of bits it is to occupy. Unnamed fields are allowed. They do not affect the meaning of the named fields, but they can be used to make the layout better in some machine-dependent way: struct PPN { // R6000 Physical Page Number unsigned int PFN : 22; // Page Frame Number int:3; // unused unsigned int CCA : 3; // Cache Coherency Algorithm bool nonreachable : 1; bool dirty : 1; bool valid : 1; bool global : 1; }; This example also illustrates the other main use of fields: to name parts of an externally imposed layout. A field must be of an integral or enumeration type (§6.2.1). It is not possible to take the address of a field. Apart from that, however, it can be used exactly like other variables. Note that a bool field really can be represented by a single bit. In an operating system kernel or in a debugger, the type PPN might be used like this: void part_of_VM _system(PPN∗ p) { // ...
ptg10564057 Section 8.2 .7 Fields 213 if (p−>dirty) { // contents changed // copy to disk p−>dirty = 0; } } Surprisingly, using fields to pack several variables into a single byte does not necessarily save space. It saves data space, but the size of the code needed to manipulate these variables increases on most machines. Programs have been known to shrink significantly when binary variables were converted from bit-fields to characters! Furthermore, it is typically much faster to access a char or an int than to access a field. Fields are simply a convenient shorthand for using bitwise logical operators (§11.1 .1) to extract information from and insert information into part of a word. 8.3 Unions A union is a struct in which all members are allocated at the same address so that the union occu- pies only as much space as its largest member. Naturally, a union can hold a value for only one member at a time. For example, consider a symbol table entry that holds a name and a value: enum Type { str, num }; struct Entry { char∗ name; Type t; char∗ s; // use s if t==str int i; // use i if t==num }; void f(Entry∗ p) { if (p−>t == str) cout << p−>s; // ... } The members s and i can never be used at the same time, so space is wasted. It can be easily recov- ered by specifying that both should be members of a union, like this: union Value { char∗ s; int i; }; The language doesn’t keep track of which kind of value is held by a union, so the programmer must do that:
ptg10564057 214 Structures, Unions, and Enumerations Chapter 8 struct Entry { char∗ name; Type t; Value v; // use v.s if t==str; use v.i if t==num }; void f(Entry∗ p) { if (p−>t == str) cout << p−>v.s; // ... } To avoid errors, one can encapsulate a union so that the correspondence between a type field and access to the union members can be guaranteed (§8.3 .2). Unions are sometimes misused for ‘‘type conversion.’’ This misuse is practiced mainly by pro- grammers trained in languages that do not have explicit type conversion facilities, so that cheating is necessary. For example, the following ‘‘converts’’ an int to an int∗ simply by assuming bitwise equivalence: union Fudge { int i; int∗ p; }; int∗ cheat(int i) { Fudge a; a.i=i; return a.p; // bad use } This is not really a conversion at all. On some machines, an int and an int∗ do not occupy the same amount of space, while on others, no integer can have an odd address. Such use of a union is dan- gerous and nonportable. If you need such an inherently ugly conversion, use an explicit type con- version operator (§11.5 .2) so that the reader can see what is going on. For example: int∗ cheat2(int i) { return reinterpret_cast<int∗>(i); // obviously ugly and dangerous } Here, at least the compiler has a chance to warn you if the sizes of objects are different and such code stands out like the sore thumb it is. Use of unions can be essential for compactness of data and through that for performance. How- ever, most programs don’t improve much from the use of unions and unions are rather error-prone. Consequently, I consider unions an overused feature; avoid them when you can.
ptg10564057 Section 8.3 .1 Unions and Classes 215 8.3.1 Unions and Classes Many nontrivial unions have a member that is much larger than the most frequently used members. Because the size of a union is at least as large as its largest member, space is wasted. This waste can often be eliminated by using a set of derived classes (§3.2.2, Chapter 20) instead of a union. Technically, a union is a kind of a struct (§8.2) which in turn is a kind of a class (Chapter 16). However, many of the facilities provided for classes are not relevant for unions, so some restrictions are imposed on unions: [1] A union cannot have virtual functions. [2] A union cannot have members of reference type. [3] A union cannot have base classes. [4] If a union has a member with a user-defined constructor, a copy operation, a move opera- tion, or a destructor, then that special function is deleted (§3.3 .4, §17.6 .4) for that union; that is, it cannot be used for an object of the union type. [5] At most one member of a union can have an in-class initializer (§17.4.4). [6] A union cannot be used as a base class. These restrictions prevent many subtle errors and simplify the implementation of unions. The latter is important because the use of unions is often an optimization and we won’t want ‘‘hidden costs’’ imposed to compromise that. The rule that deletes constructors (etc.) from a union with a member that has a constructor (etc.) keeps simple unions simple and forces the programmer to provide complicated operations if they are needed. For example, since Entry has no member with constructors, destructors, or assign- ments, we can create and copy Entrys freely. For example: void f(Entry a) { Entryb=a; }; Doing so with a more complicated union would cause implementation difficulties or errors: union U { int m1; complex<double> m2; // complex has a constructor string m3; // string has a constructor (maintaining a serious invariant) }; To c o py a U we would have to decide which copy operation to use. For example: void f2(U x) { Uu; //error: which default constructor? Uu2=x; //error: which copy constructor? u.m1 = 1; // assign to int member string s = u.m3; // disaster: read from string member return; // error: which destructors are called for x, u, and u2? } It’s illegal to write one member and then read another, but people do that nevertheless (usually by mistake). In this case, the string copy constructor would be called with an invalid argument. It is
ptg10564057 216 Structures, Unions, and Enumerations Chapter 8 fortunate that U won’t compile. When needed, a user can define a class containing a union that properly handles union members with constructors, destructors, and assignments (§8.3.2). If desired, such a class can also prevent the error of writing one member and then reading another. It is possible to specify an in-class initializer for at most one member. If so, this initializer will be used for default initialization. For example: union U2 { int a; const char∗ p {""}; }; U2 x1; // default initialized to x1.p == "" U2 x2 {7}; //x2.a ==7 8.3.2 Anonymous unions To see how we can write a class that overcomes the problems with misuse of a union, consider a variant of Entry (§8.3): class Entry2 { // two alternative representations represented as a union private: enum class Tag { number, text }; Tag type; // discriminant union { // representation int i; string s; // string has default constructor, copy operations, and destructor }; public: struct Bad_entry { }; // used for exceptions string name; ̃Entry2(); Entry2& operator=(const Entry2&); // necessary because of the string variant Entry2(const Entry2&); // ... int number() const; string text() const; void set_number(int n); void set_text(const string&); // ... }; I’m not a fan of get/set functions, but in this case we really need to perform a nontrivial user-speci- fied action on each access. I chose to name the ‘‘get’’ function after the value and use the set_ pre- fix for the ‘‘set’’ function. That happens to be my favorite among the many naming conventions.
ptg10564057 Section 8.3 .2 Anonymous unions 217 The read-access functions can be defined like this: int Entry2::number() const { if (type!=Tag::number) throw Bad_entry{}; return i; }; string Entry2::text() const { if (type!=Tag::text) throw Bad_entry{}; return s; }; These access functions check the type tag, and if it is the one that correctly corresponds to the access we want, it returns a reference to the value; otherwise, it throws an exception. Such a union is often called a tagged union or a discriminated union. The write-access functions basically do the same checking of the type tag, but note how setting a new value must take the previous value into account: void Entry2::set_number(int n) { if (type==Tag::text) { s. ̃string(); // explicitly destroy string (§11.2.4) type = Tag::number; } i=n; } void Entry2::set_text(const string& ss) { if (type==Tag::text) s=ss; else { new(&s) string{ss}; // placement new: explicitly construct string (§11.2 .4) type = Tag::text; } } The use of a union forces us to use otherwise obscure and low-level language facilities (explicit construction and destruction) to manage the lifetime of the union elements. This is another reason to be wary of using unions. Note that the union in the declaration of Entry2 is not named. That makes it an anonymous union. An anonymous union is an object, not a type, and its members can be accessed without mentioning an object name. That means that we can use members of an anonymous union exactly as we use other members of a class – as long as we remember that union members really can be used only one at a time. Entry2 has a member of a type with a user-defined assignment operator, string,soEntry2’s assignment operator is deleted (§3.3 .4, §17.6 .4). If we want to assign Entry2s, we have to define
ptg10564057 218 Structures, Unions, and Enumerations Chapter 8 Entry2::operator=(). Assignment combines the complexities of reading and writing but is otherwise logically similar to the access functions: Entry2& Entry2::operator=(const Entry2& e) // necessary because of the string variant { if (type==Tag::text && e.type==Tag::text) { s=e.s; //usual string assignment return ∗this; } if (type==Tag::text) s.̃ string(); // explicit destroy (§11.2 .4) switch (e.type) { case Tag::number: i=e.i; break; case Tag::text: new(&s)(e.s); // placement new: explicit construct (§11.2.4) type = e .type; } return ∗this; } Constructors and a move assignment can be defined similarly as needed. We need at least a con- structor or two to establish the correspondence between the type tag and a value. The destructor must handle the string case: Entry2::̃Entry2() { if (type==Tag::text) s.̃ string(); // explicit destroy (§11.2 .4) } 8.4 Enumerations An enumeration is a type that can hold a set of integer values specified by the user (§iso.7 .2). Some of an enumeration’s possible values are named and called enumerators. For example: enum class Color { red, green, blue }; This defines an enumeration called Color with the enumerators red, green, and blue. ‘‘An enumera- tion’’ is colloquially shortened to ‘‘an enum.’’ There are two kinds of enumerations: [1] enum classes, for which the enumerator names (e.g ., red) are local to the enum and their values do not implicitly convert to other types [2] ‘‘Plain enums,’’ for which the enumerator names are in the same scope as the enum and their values implicitly convert to integers In general, prefer the enum classes because they cause fewer surprises.
ptg10564057 Section 8.4 .1 enum classes 219 8.4.1 enum classes An enum class is a scoped and strongly typed enumeration. For example: enum class Traffic_light { red, yellow, green }; enum class Warning { green, yellow, orange, red }; // fire alert levels Warning a1 = 7; // error: no int->Warning conversion int a2 = green; // error: green not in scope int a3 = Warning::green; // error: no Warning->int conversion Warning a4 = Warning::green; // OK void f(Traffic_light x) { if(x==9){/* ...*/} // error: 9 is not a Traffic_light if(x==red){/* ... */} // error: no red in scope if (x == Warning::red) { /* ... */ } // error: x is not a Warning if (x == Traffic_light::red) { /* ... */ } // OK } Note that the enumerators present in both enums do not clash because each is in the scope of its own enum class. An enumeration is represented by some integer type and each enumerator by some integer value. We call the type used to represent an enumeration its underlying type. The underlying type must be one of the signed or unsigned integer types (§6.2.4); the default is int. We could be explicit about that: enum class Warning : int { green, yellow, orange, red }; // sizeof(Warning)==sizeof(int) If we considered that too wasteful of space, we could instead use a char: enum class Warning : char { green, yellow, orange, red }; // sizeof(Warning)==1 By default, enumerator values are assigned increasing from 0. Here, we get: static_cast<int>(Warning::green)==0 static_cast<int>(Warning::yellow)==1 static_cast<int>(Warning::orange)==2 static_cast<int>(Warning::red)==3 Declaring a variable Warning instead of plain int can give both the user and the compiler a hint as to the intended use. For example: void f(Warning key) { switch (key) { case Warning::green: // do something break; case Warning::orange: // do something break;
ptg10564057 220 Structures, Unions, and Enumerations Chapter 8 case Warning::red: // do something break; } } A human might notice that yellow was missing, and a compiler might issue a warning because only three out of four Warning values are handled. An enumerator can be initialized by a constant expression (§10.4) of integral type (§6.2 .1). For example: enum class Printer_flags { acknowledge=1, paper_empty=2, busy=4, out_of_black=8, out_of_color=16, // }; The values for the Printer_flags enumerators are chosen so that they can be combined by bitwise operations. An enum is a user-defined type, so we can define the | and & operators for it (§3.2 .1 .1, Chapter 18). For example: constexpr Printer_flags operator|(Printer_flags a, Printer_flags b) { return static_cast<Printer_flags>(static_cast<int>(a))|static_cast<int>(b)); } constexpr Printer_flags operator&(Printer_flags a, Printer_flags b) { return static_cast<Printer_flags>(static_cast<int>(a))&static_cast<int>(b)); } The explicit conversions are necessary because a class enum does not support implicit conversions. Given these definitions of | and & for Printer_flags, we can write: void try_to_print(Printer_flags x) { if (x&Printer_flags::acknowledge) { // ... } else if (x&Printer_flags::busy) { // ... } else if (x&(Printer_flags::out_of_black|Printer_flags::out_of_color)) { // either we are out of black or we are out of color // ... } // ... }
ptg10564057 Section 8.4 .1 enum classes 221 I defined operator|() and operator&() to be constexpr functions (§10.4, §12.1 .6) because someone might want to use those operators in constant expressions. For example: void g(Printer_flags x) { switch (x) { case Printer_flags::acknowledge: // ... break; case Printer_flags::busy: // ... break; case Printer_flags::out_of_black: // ... break; case Printer_flags::out_of_color: // ... break; case Printer_flags::out_of_black&Printer_flags::out_of_color: // we are out of black *and* out of color // ... break; } // ... } It is possible to declare an enum class without defining it (§6.3) until later. For example: enum class Color_code : char; // declaration void foobar(Color_code∗ p); // use of declaration // ... enum class Color_code : char { // definition red, yellow, green, blue }; A value of integral type may be explicitly converted to an enumeration type. The result of such a conversion is undefined unless the value is within the range of the enumeration’s underlying type. For example: enum class Flag : char{ x=1, y=2, z=4, e=8 }; Flag f0 {}; // f0 gets the default value 0 Flagf1=5; // type error: 5 is not of type Flag Flag f2 = Flag{5}; // error: no narrowing conversion to an enum class Flag f3 = static_cast<Flag>(5); // brute force Flag f4 = static_cast<Flag>(999); // error: 999 is not a char value (maybe not caught) The last assignments show why there is no implicit conversion from an integer to an enumeration; most integer values do not have a representation in a particular enumeration.
ptg10564057 222 Structures, Unions, and Enumerations Chapter 8 Each enumerator has an integer value. We can extract that value explicitly. For example: int i = static_cast<int>(Flag::y); // i becomes 2 char c = static_cast<char>(Flag::e); // c becomes 8 The notion of a range of values for an enumeration differs from the enumeration notion in the Pas- cal family of languages. However, bit-manipulation examples that require values outside the set of enumerators to be well defined (e.g ., the Printer_flags example) have a long history in C and C++. The sizeof an enum class is the sizeof of its underlying type. In particular, if the underlying type is not explicitly specified, the size is sizeof(int). 8.4.2 Plain enums A ‘‘plain enum’’ is roughly what C++ offered before the enum classes were introduced, so you’ll find them in lots of C and C++98-style code. The enumerators of a plain enum are exported into the enum’s scope, and they implicitly convert to values of some integer type. Consider the exam- ples from §8.4 .1 with the ‘‘class’’ removed: enum Traffic_light { red, yellow, green }; enum Warning { green, yellow, orange, red }; // fire alert levels // error: two definitions of yellow (to the same value) // error: two definitions of red (to different values) Warning a1 = 7; // error: no int->Warning conversion int a2 = green; // OK: green is in scope and converts to int int a3 = Warning::green; // OK: Warning->int conversion Warning a4 = Warning::green; // OK void f(Traffic_light x) { if(x==9){/* ...*/} // OK (but Traffic_light doesn’t have a 9) if(x==red){/* ... */} // error: two reds in scope if (x == Warning::red) { /* ... */ } // OK (Ouch!) if (x == Traffic_light::red) { /* ... */ } // OK } We were ‘‘lucky’’ that defining red in two plain enumerations in a single scope saved us from hard- to-spot errors. Consider ‘‘cleaning up’’ the plain enums by disambiguating the enumerators (as is easily done in a small program but can be done only with great difficulty in a large one): enum Traffic_light { tl_red, tl_yellow, tl_green }; enum Warning { green, yellow, orange, red }; // fire alert levels
ptg10564057 Section 8.4 .2 Plain enums 223 void f(Traffic_light x) { if(x==red){/* ... */} // OK (ouch!) if (x == Warning::red) { /* ... */ } // OK (ouch!) if (x == Traffic_light::red) { /* ... */ } // error: red is not a Traffic_light value } The compiler accepts the x==red, which is almost certainly a bug. The injection of names into an enclosing scope (as enums, but not enum classes or classes, do) is namespace pollution and can be a major problem in larger programs (Chapter 14). You can specify the underlying type of a plain enumeration, just as you can for enum classes. If you do, you can declare the enumerations without defining them until later. For example: enum Traffic_light : char { tl_red, tl_yellow, tl_green }; // underlying type is char enum Color_code : char; // declaration void foobar(Color_code∗ p); // use of declaration // ... enum Color_code : char { red, yellow, green, blue }; // definition If you don’t specify the underlying type, you can’t declare the enum without defining it, and its underlying type is determined by a relatively complicated algorithm: when all enumerators are non- negative, the range of the enumeration is [0:2 k -1]where2 k is the smallest power of 2 for which all enumerators are within the range. If there are negative enumerators, the range is [-2 k :2 k - 1]. This defines the smallest bit-field capable of holding the enumerator values using the conventional two’s complement representation. For example: enum E1 { dark, light }; // range 0:1 enumE2{a=3,b=9}; // range 0:15 enum E3 { min = −10, max = 1000000 }; // range -1048576:1048575 The rule for explicit conversion of an integer to a plain enum is the same as for the class enum except that when there is no explicit underlying type, the result of such a conversion is undefined unless the value is within the range of the enumeration. For example: enum Flag { x=1, y=2, z=4, e=8 }; // range 0:15 Flag f0 {}; // f0 gets the default value 0 Flagf1=5; // type error: 5 is not of type Flag Flag f2 = Flag{5}; // error: no explicit conversion from int to Flag Flag f2 = static_cast<Flag>(5); // OK: 5 is within the range of Flag Flag f3 = static_cast<Flag>(z|e); // OK: 12 is within the range of Flag Flag f4 = static_cast<Flag>(99); // undefined: 99 is not within the range of Flag Because there is an implicit conversion from a plain enum to its underlying type, we don’t need to define | to make this example work: z and e are converted to int so that z|e can be evaluated. The sizeof an enumeration is the sizeof its underlying type. If the underlying type isn’t explicitly speci- fied, it is some integral type that can hold its range and not larger than sizeof(int), unless an enumer- ator cannot be represented as an int or as an unsigned int. For example, sizeof(e1) could be 1 or maybe 4 but not 8 on a machine where sizeof(int)==4.
ptg10564057 224 Structures, Unions, and Enumerations Chapter 8 8.4.3 Unnamed enums A plain enum can be unnamed. For example: enum { arrow_up=1, arrow_down, arrow_sideways }; We use that when all we need is a set of integer constants, rather than a type to use for variables. 8.5 Advice [1] When compactness of data is important, lay out structure data members with larger members before smaller ones; §8.2 .1. [2] Use bit-fields to represent hardware-imposed data layouts; §8.2 .7 . [3] Don’t naively try to optimize memory consumption by packing several values into a single byte; §8.2 .7 . [4] Use unions to save space (represent alternatives) and never for type conversion; §8.3 . [5] Use enumerations to represent sets of named constants; §8.4 . [6] Prefer class enums over ‘‘plain’’ enums to minimize surprises; §8.4 . [7] Define operations on enumerations for safe and simple use; §8.4 .1 .
ptg10564057 9 Statements A programmer is a machine for turning caffeine into code. – A programmer • Introduction • Statement Summary • Declarations as Statements • Selection Statements if Statements; switch Statements; Declarations in Conditions • Iteration Statements Range-for Statements; for Statements; while Statements; do Statements; Loop exit • goto Statements • Comments and Indentation • Advice 9.1 Introduction C++ offers a conventional and flexible set of statements. Basically all that is either interesting or complicated is found in expressions and declarations. Note that a declaration is a statement and that an expression becomes a statement when you add a semicolon at its end. Unlike an expression, a statement does not have a value. Instead, statements are used to specify the order of execution. For example: a=b+c; // expression statement if (a==7) // if-statement b=9; //execute if and only if a==9 Logically, a=b+c is executed before the if, as everyone would expect. A compiler may reorder code to improve performance as long as the result is identical to that of the simple order of execution.
ptg10564057 226 Statements Chapter 9 9.2 Statement Summary Here is a summary of C++ statements: statement: declaration expressionopt ; { statement-listopt } try { statement-listopt } handler-list case constant-expression : statement default : statement break ; continue ; return expressionopt ; goto identifier ; identifier : statement selection-statement iteration-statement selection-statement: if ( condition ) statement if ( condition ) statement else statement switch ( condition ) statement iteration-statement: while ( condition ) statement do statement while ( expression ); for ( for-init-statement conditionopt ; expressionopt ) statement for ( for-init-declaration : expression ) statement statement-list: statement statement-listopt condition: expression type-specifier declarator = expression type-specifier declarator { expression } handler-list: handler handler-listopt handler: catch ( exception-declaration ){statement-listopt } A semicolon is by itself a statement, the empty statement.
ptg10564057 Section 9.2 Statement Summary 227 A (possibly empty) sequence of statements within ‘‘curly braces’’ (i.e ., { and }) is called a block or a compound statement. A name declared in a block goes out of scope at the end of its block (§6.3 .4). A declaration is a statement and there is no assignment statement or procedure-call statement; assignments and function calls are expressions. A for-init-statement must be either a declaration or an expression-statement. Note that both end with a semicolon. A for-init-declaration must be the declaration of a single uninitialized variable. The statements for handling exceptions, try-blocks, are described in §13.5 . 9.3 Declarations as Statements A declaration is a statement. Unless a variable is declared static, its initializer is executed whenever the thread of control passes through the declaration (see also §6.4.2). The reason for allowing dec- larations wherever a statement can be used (and a few other places; §9.4 .3, §9.5 .2) is to enable the programmer to minimize the errors caused by uninitialized variables and to allow better locality in code. There is rarely a reason to introduce a variable before there is a value for it to hold. For example: void f(vector<string>& v, int i, const char∗ p) { if (p==nullptr) return; if (i<0 || v.size()<=i) error("bad index"); string s = v[i]; if(s==p){ // ... } // ... } The ability to place declarations after executable code is essential for many constants and for sin- gle-assignment styles of programming where a value of an object is not changed after initialization. For user-defined types, postponing the definition of a variable until a suitable initializer is available can also lead to better performance. For example: void use() { string s1; s1 = "The best is the enemy of the good."; // ... } This requests a default initialization (to the empty string) followed by an assignment. This can be slower than a simple initialization to the desired value: string s2 {"Voltaire"}; The most common reason to declare a variable without an initializer is that it requires a statement
ptg10564057 228 Statements Chapter 9 to give it its desired value. Input variables are among the few reasonable examples of that: void input() { int buf[max]; int count = 0; for (int i; cin>>i;) { if (i<0) error("unexpected negative value"); if (count==max) error("buffer overflow"); buf[count++] = i; } // ... } I assume that error() does not return; if it does, this code may cause a buffer overflow. Often, push_back() (§3.2 .1 .3, §13.6, §31.3.6) provides a better solution to such examples. 9.4 Selection Statements A value can be tested by either an if-statement or a switch-statement: if ( condition ) statement if ( condition ) statement else statement switch ( condition ) statement A condition is either an expression or a declaration (§9.4 .3). 9.4.1 if Statements In an if-statement, the first (or only) statement is executed if the condition is true and the second statement (if it is specified) is executed otherwise. If a condition evaluates to something different from a Boolean, it is – if possible – implicitly converted to a bool. This implies that any arithmetic or pointer expression can be used as a condition. For example, if x is an integer, then if (x) // ... means if(x!=0)//... For a pointer p, if (p) // ... is a direct statement of the test ‘‘Does p point to a valid object (assuming proper initialization)?’’ and is equivalent to if (p != nullptr) // ... Note that a ‘‘plain’’ enum can be implicitly converted to an integer and then to a bool, whereas an enum class cannot (§8.4 .1). For example:
ptg10564057 Section 9.4 .1 if Statements 229 enumE1{a,b}; enumclassE2{a,b}; void f(E1 x, E2 y) { if (x) // OK // ... if (y) // error: no conversion to bool // ... if (y==E2::a) // OK // ... } The logical operators &&||! are most commonly used in conditions. The operators && and || will not evaluate their second argu- ment unless doing so is necessary. For example, if (p && 1<p−>count) // ... This tests 1<p−>count only if p is not nullptr. For choosing between two alternatives each of which produces a value, a conditional expression (§11.1.3) is a more direct expression of intent than an if-statement. For example: int max(int a, int b) { return (a>b)?a:b; // return the larger of a and b } A name can only be used within the scope in which it is declared. In particular, it cannot be used on another branch of an if-statement. For example: void f2(int i) { if(i){ intx=i+2; ++x; // ... } else { ++x; // error: x is not in scope } ++x; // error: x is not in scope } A branch of an if-statement cannot be just a declaration. If we need to introduce a name in a branch, it must be enclosed in a block (§9.2). For example:
ptg10564057 230 Statements Chapter 9 void f1(int i) { if (i) intx=i+2; // error: declaration of if-statement branch } 9.4.2 switch Statements A switch-statement selects among a set of alternatives (case-labels). The expression in the case labels must be a constant expression of integral or enumeration type. A value may not be used more than once for case-labels in a switch-statement. For example: void f(int i) { switch (i) { case 2.7: // error: floating point uses for case // ... case 2: // ... case 4−2: // error: 2 used twice in case labels // ... }; A switch-statement can alternatively be written as a set of if-statements. For example: switch (val) { case 1: f(); break; case 2: g(); break; default: h(); break; } This could be expressed as: if (val == 1) f(); else if (val == 2) g(); else h(); The meaning is the same, but the first (switch) version is preferred because the nature of the opera- tion (testing a single value against a set of constants) is explicit. This makes the switch-statement easier to read for nontrivial examples. It typically also leads to the generation of better code because there is no reason to repeatedly check individual values. Instead, a jump table can be used.
ptg10564057 Section 9.4 .2 switch Statements 231 Beware that a case of a switch must be terminated somehow unless you want to carry on execut- ing the next case. Consider: switch (val) { // beware case 1: cout << "case 1\n"; case 2: cout << "case 2\n"; default: cout << "default: case not found\n"; } Invoked with val==1, the output will greatly surprise the uninitiated: case 1 case 2 default: case not found It is a good idea to comment the (rare) cases in which a fall-through is intentional so that an uncom- mented fall-through can be assumed to be an error. For example: switch (action) { // handle (action,value) pair case do_and_print: act(value); // no break: fall through to print case print: print(value); break; // ... } A break is the most common way of terminating a case, but a return is often useful (§10.2 .1). When should a switch-statement have a default? There is no single answer that covers all situa- tions. One use is for the default to handle the most common case. Another common use is the exact opposite: the default: action is simply a way to catch errors; every valid alternative is covered by the cases. However, there is one case where a default should not be used: if a switch is intended to have one case for each enumerator of an enumeration. If so, leaving out the default gives the compiler a chance to warn against a set of cases that almost but not quite match the set of enumera- tors. For example, this is almost certainly an error: enum class Vessel { cup, glass, goblet, chalice }; void problematic(Vessel v) { switch (v) { case Vessel::cup: /* ... */ break; case Vessel::glass: /* ... */ break; case Vessel::goblet: /* ... */ break; } }
ptg10564057 232 Statements Chapter 9 Such a mistake can easily occur when a new enumerator is added during maintenance. Testing for an ‘‘impossible’’ enumerator value is best done separately. 9.4 .2.1 Declarations in Cases It is possible, and common, to declare variables within the block of a switch-statement. However, it is not possible to bypass an initialization. For example: void f(int i) { switch (i) { case 0: int x; // uninitialized inty=3; // error: declaration can be bypassed (explicitly initialized) string s; // error: declaration can be bypassed (implicitly initialized) case 1: ++x; // error: use of uninitialized object ++y; s = "nasty!"; } } Here, if i==1, the thread of execution would bypass the initializations of y and s,sof() will not com- pile. Unfortunately, because an int needn’t be initialized, the declaration of x is not an error. How- ever, its use is an error: we read an uninitialized variable. Unfortunately, compilers often give just a warning for the use of an uninitialized variable and cannot reliably catch all such misuses. As usual, avoid uninitialized variables (§6.3 .5 .1). If we need a variable within a switch-statement, we can limit its scope by enclosing its declara- tion and its use in a block. For an example, see prim() in §10.2 .1 . 9.4.3 Declarations in Conditions To avoid accidental misuse of a variable, it is usually a good idea to introduce the variable into the smallest scope possible. In particular, it is usually best to delay the definition of a local variable until one can give it an initial value. That way, one cannot get into trouble by using the variable before its initial value is assigned. One of the most elegant applications of these two principles is to declare a variable in a condi- tion. Consider: if (double d = prim(true)) { left /= d; break; } Here, d is declared and initialized and the value of d after initialization is tested as the value of the condition. The scope of d extends from its point of declaration to the end of the statement that the condition controls. For example, had there been an else-branch to the if-statement, d would be in scope on both branches.
ptg10564057 Section 9.4 .3 Declarations in Conditions 233 The obvious and traditional alternative is to declare d before the condition. However, this opens the scope (literally) for the use of d before its initialization or after its intended useful life: double d; // ... d2=d; //oops! // ... if (d = prim(true)) { left /= d; break; } // ... d = 2.0; // two unrelated uses of d In addition to the logical benefits of declaring variables in conditions, doing so also yields the most compact source code. A declaration in a condition must declare and initialize a single variable or const. 9.5 Iteration Statements A loop can be expressed as a for-, while-, or do-statement: while ( condition ) statement do statement while ( expression ); for ( for-init-statement conditionopt ; expressionopt ) statement for ( for-declaration : expression ) statement A for-init-statement must be either a declaration or an expression-statement. Note that both end with a semicolon. The statement of a for-statement (called the controlled statement or the loop body) is executed repeatedly until the condition becomes false or the programmer breaks out of the loop some other way (such as a break,areturn,athrow,oragoto). More complicated loops can be expressed as an algorithm plus a lambda expression (§11.4 .2). 9.5.1 Range-for Statements The simplest loop is a range-for-statement; it simply gives the programmer access to each element of a range. For example: int sum(vector<int>& v) { ints=0; for(intx:v) s+=x; return s; }
ptg10564057 234 Statements Chapter 9 The for (int x : v) can be read as ‘‘for each element x in the range v’’ or just ‘‘for each x in v.’’ The elements of v are visited in order from the first to the last. The scope of the variable naming the element (here, x)isthefor-statement. The expression after the colon must denote a sequence (a range); that is, it must yield a value for which we can call v.begin() and v.end() or begin(v) and end(v) to obtain an iterators (§4.5): [1] the compiler first looks for members begin and end and tries to use those. If a begin or an end is found that cannot be used as a range (e.g ., because a member begin is a variable rather than a function), the range-for is an error. [2] Otherwise, the compiler looks for a begin/end member pair in the enclosing scope. If none is found or if what is found cannot be used (e.g ., because the begin did not take an argument of the sequence’s type), the range-for is an error. The compiler uses v and v+N as begin(v) and end(v) for a built-in array T v[N]. The <iterator> header provides begin(c) and end(c) for built-in arrays and for all standard-library containers. For sequences of our own design, we can define begin() and end() in the same way as it is done for stan- dard-library containers (§4.4 .5). The controlled variable, x in the example, that refers to the current element is equivalent to ∗p when using an equivalent for-statement: int sum2(vector<int>& v) { ints=0; for (auto p = begin(v); p!=end(v); ++p) s+=∗p; return s; } If you need to modify an element in a range-for loop, the element variable should be a reference. For example, we can increment each element of a vector like this: void incr(vector<int>& v) { for(int&x:v) ++x; } References are also appropriate for elements that might be large, so that copying them to the ele- ment value could be costly. For example: template<class T> T accum(vector<T>& v) { Tsum=0; for(constT&x:v) sum += x; return sum; } Note that a range-for loop is a deliberately simple construct. For example, using it you can’t touch two elements at the same time and can’t effectively traverse two ranges simultaneously. For that we need a general for-statement.
ptg10564057 Section 9.5 .2 for Statements 235 9.5.2 for Statements There is also a more general for-statement allowing greater control of the iteration. The loop vari- able, the termination condition, and the expression that updates the loop variable are explicitly pre- sented ‘‘up front’’ on a single line. For example: void f(int v[], int max) { for (int i = 0; i!=max; ++i) v[i] = i∗i; } This is equivalent to void f(int v[], int max) { inti=0; // introduce loop variable while (i!=max) { // test termination condition v[i] = i∗i; // execute the loop body ++i; // increment loop variable } } A variable can be declared in the initializer part of a for-statement. If that initializer is a declara- tion, the variable (or variables) it introduced is in scope until the end of the for-statement. It is not always obvious what is the right type to use for a controlled variable in a for loop, so auto often comes in handy: for (auto p = begin(c); c!=end(c); ++p) { // ... use iterator p for elements in container c ... } If the final value of an index needs to be known after exit from a for-loop, the index variable must be declared outside the for-loop (e.g ., see §9.6). If no initialization is needed, the initializing statement can be empty. If the expression that is supposed to increment the loop variable is omitted, we must update some form of loop variable elsewhere, typically in the body of the loop. If the loop isn’t of the sim- ple ‘‘introduce a loop variable, test the condition, update the loop variable’’ variety, it is often better expressed as a while-statement. However, consider this elegant variant: for (string s; cin>>s;) v.push_back(s); Here, the reading and testing for termination and combined in cin>>s, so we don’t need an explicit loop variable. On the other hand, the use of for, rather than while, allows us to limit the scope of the ‘‘current element,’’ s, to the loop itself (the for-statement). A for-statement is also useful for expressing a loop without an explicit termination condition: for (;;) { // ‘‘forever’’ // ... }
ptg10564057 236 Statements Chapter 9 However, many consider this idiom obscure and prefer to use: while(true) { // ‘‘forever’’ // ... } 9.5.3 while Statements A while-statement executes its controlled statement until its condition becomes false. For example: template<class Iter, class Value> Iter find(Iter first, Iter last, Value val) { while (first!=last && ∗first!=val) ++first; return first; } I tend to prefer while-statements over for-statements when there isn’t an obvious loop variable or where the update of a loop variable naturally comes in the middle of the loop body. A for-statement (§9.5 .2) is easily rewritten into an equivalent while-statement and vice versa. 9.5.4 do Statements A do-statement is similar to a while-statement except that the condition comes after the body. For example: void print_backwards(char a[], int i) // i must be positive { cout << '{'; do{ cout << a[−−i]; } while (i); cout << '}'; } This might be called like this: print_backwards(s,strlen(s)); but it is all too easy to make a horrible mistake. For example, what if s was the empty string? In my experience, the do-statement is a source of errors and confusion. The reason is that its body is always executed once before the condition is evaluated. However, for the body to work cor- rectly, something very much like the condition must hold even the first time through. More often than I would have guessed, I have found that condition not to hold as expected either when the pro- gram was first written and tested or later after the code preceding it has been modified. I also prefer the condition ‘‘up front where I can see it.’’ Consequently, I recommend avoiding do-statements. 9.5.5 Loop Exit If the condition of an iteration statement (a for-, while-, or do-statement) is omitted, the loop will not terminate unless the user explicitly exits it by a break, return (§12.1.4), goto (§9.6), throw (§13.5), or some less obvious way such as a call of exit() (§15.4 .3). A break ‘‘breaks out of ’’ the
ptg10564057 Section 9.5 .5 Loop Exit 237 nearest enclosing switch-statement (§9.4 .2) or iteration-statement. For example: void f(vector<string>& v, string terminator) { char c; string s; while (cin>>c) { // ... if (c == '\n') break; // ... } } We use a break when we need to leave the loop body ‘‘in the middle.’’ Unless it warps the logic of a loop (e.g., requires the introduction of an extra varible), it is usually better to have the complete exit condition as the condition of a while-statement or a for-statement. Sometimes, we don’t want to exit the loop completely, we just want to get to the end of the loop body. A continue skips the rest of the body of an iteration-statement. For example: void find_prime(vector<string>& v) { for (int i = 0; i!=v.size(); ++i) { if (!prime(v[i]) continue; return v[i]; } } After a continue, the increment part of the loop (if any) is executed, followed by the loop condition (if any). So find_prime() could equivalently have been written as: void find_prime(vector<string>& v) { for (int i = 0; i!=v.size(); ++i) { if (!prime(v[i]) { return v[i]; } } } 9.6 goto Statements C++ possesses the infamous goto: goto identifier ; identifier : statement The goto has few uses in general high-level programming, but it can be very useful when C++ code is generated by a program rather than written directly by a person; for example, gotos can be used in a parser generated from a grammar by a parser generator.
ptg10564057 238 Statements Chapter 9 The scope of a label is the function it is in (§6.3 .4). This implies that you can use goto to jump both into and out of blocks. The only restriction is that you cannot jump past an initializer or into an exception handler (§13.5). One of the few sensible uses of goto in ordinary code is to break out from a nested loop or switch-statement (a break breaks out of only the innermost enclosing loop or switch-statement). For example: void do_something(int i, int j) // do something to a two-dimensional matrix called mn { for (i = 0; i!=n; ++i) for (j = 0; j!=m; ++j) if (nm[i][j] == a) goto found; // not found // ... found: // nm[i][j] == a } Note that this goto just jumps forward to exit its loop. It does not introduce a new loop or enter a new scope. That makes it the least troublesome and least confusing use of a goto. 9.7 Comments and Indentation Judicious use of comments and consistent use of indentation can make the task of reading and understanding a program much more pleasant. Several different consistent styles of indentation are in use. I see no fundamental reason to prefer one over another (although, like most programmers, I have my preferences, and this book reflects them). The same applies to styles of comments. Comments can be misused in ways that seriously affect the readability of a program. The com- piler does not understand the contents of a comment, so it has no way of ensuring that a comment • is meaningful, • describes the program, and • is up to date. Most programs contain comments that are incomprehensible, ambiguous, and just plain wrong. Bad comments can be worse than no comments. If something can be stated in the language itself, it should be, and not just mentioned in a com- ment. This remark is aimed at comments such as these: // variable "v" must be initialized // variable "v" must be used only by function "f()" // call function "init()" before calling any other function in this file // call function "cleanup()" at the end of your program
ptg10564057 Section 9.7 Comments and Indentation 239 // don’t use function "weird()" // function "f(int ...)" takes two or three arguments Such comments can typically be rendered unnecessary by proper use of C++. Once something has been stated clearly in the language, it should not be mentioned a second time in a comment. For example: a = b+c; // a becomes b+c count++; // increment the counter Such comments are worse than simply redundant. They increase the amount of text the reader has to look at, they often obscure the structure of the program, and they may be wrong. Note, however, that such comments are used extensively for teaching purposes in programming language textbooks such as this. This is one of the many ways a program in a textbook differs from a real program. A good comment states what a piece of code is supposed to do (the intent of the code), whereas the code (only) states what it does (in terms of how it does it). Preferably, a comment is expressed at a suitably high level of abstraction so that it is easy for a human to understand without delving into minute details. My preference is for: • A comment for each source file stating what the declarations in it have in common, refer- ences to manuals, the name of the programmer, general hints for maintenance, etc. • A comment for each class, template, and namespace • A comment for each nontrivial function stating its purpose, the algorithm used (unless it is obvious), and maybe something about the assumptions it makes about its environment • A comment for each global and namespace variable and constant • A few comments where the code is nonobvious and/or nonportable • Very little else For example: // tbl.c: Implementation of the symbol table. /* Gaussian elimination with partial pivoting. See Ralston: "A first course ..." pg 411. */ // scan(p,n,c) requires that p points to an array of at least n elements // sort(p,q) sorts the elements of the sequence [p:q) using < for comparison. // Revised to handle invalid dates. Bjarne Stroustrup, Feb 29 2013 A well-chosen and well-written set of comments is an essential part of a good program. Writing good comments can be as difficult as writing the program itself. It is an art well worth cultivating.
ptg10564057 240 Statements Chapter 9 Note that /∗∗/ style comments do not nest. For example: /* remove expensive check if (check(p,q)) error("bad p q") /* should never happen */ ∗/ This nesting should give an error for an unmatched final ∗/. 9.8 Advice [1] Don’t declare a variable until you have a value to initialize it with; §9.3, §9.4.3, §9.5.2 . [2] Prefer a switch-statement to an if-statement when there is a choice; §9.4 .2. [3] Prefer a range-for-statement to a for-statement when there is a choice; §9.5 .1 . [4] Prefer a for-statement to a while-statement when there is an obvious loop variable; §9.5 .2 . [5] Prefer a while-statement to a for-statement when there is no obvious loop variable; §9.5 .3 . [6] Avoid do-statements; §9.5 . [7] Avoid goto; §9.6 . [8] Keep comments crisp; §9.7 . [9] Don’t say in comments what can be clearly stated in code; §9.7 . [10] State intent in comments; §9.7 . [11] Maintain a consistent indentation style; §9.7.
ptg10564057 10 Expressions Programming is like sex: It may give some concrete results, but that is not why we do it. – apologies to Richard Feynman • Introduction • A Desk Calculator The Parser; Input; Low-Level Input; Error Handling; The Driver; Headers; Command-Line Arguments; A Note on Style • Operator Summary Results; Order of Evaluation; Operator Precedence; Temporary Objects • Constant Expressions Symbolic Constants; consts in Constant Expressions; Literal Types; Reference Arguments; Address Constant Expressions • Implicit Type Conversion Promotions; Conversions; Usual Arithmetic Conversions • Advice 10.1 Introduction This chapter discusses expressions in some detail. In C++, an assignment is an expression, a func- tion call is an expression, the construction of an object is an expression, and so are many other operations that go beyond conventional arithmetic expression evaluation. To give an impression of how expressions are used and to show them in context, I first present a small complete program, a simple ‘‘desk calculator.’’ Next, the complete set of operators is listed and their meaning for built- in types is briefly outlined. The operators that require more extensive explanation are discussed in Chapter 11.
ptg10564057 242 Expressions Chapter 10 10.2 A Desk Calculator Consider a simple desk calculator program that provides the four standard arithmetic operations as infix operators on floating-point numbers. The user can also define variables. For example, given the input r=2.5 area=pi∗r∗r (pi is predefined) the calculator program will write 2.5 19.635 where 2.5 is the result of the first line of input and 19.635 is the result of the second. The calculator consists of four main parts: a parser, an input function, a symbol table, and a driver. Actually, it is a miniature compiler in which the parser does the syntactic analysis, the input function handles input and lexical analysis, the symbol table holds permanent information, and the driver handles initialization, output, and errors. We could add many features to this calculator to make it more useful, but the code is long enough as it is, and most features would just add code without providing additional insight into the use of C++. 10.2.1 The Parser Here is a grammar for the language accepted by the calculator: program: end // end is end-of-input expr_list end expr_list: expression print // print is newline or semicolon expression print expr_list expression: expression + term expression − term term term: term / primary term ∗ primary primary primary: number // number is a floating-point literal name // name is an identifier name = expression − primary ( expression )
ptg10564057 Section 10.2 .1 The Parser 243 In other words, a program is a sequence of expressions separated by semicolons. The basic units of an expression are numbers, names, and the operators ∗, /, +, − (both unary and binary), and = (assignment). Names need not be declared before use. I use a style of syntax analysis called recursive descent; it is a popular and straightforward top- down technique. In a language such as C++, in which function calls are relatively cheap, it is also efficient. For each production in the grammar, there is a function that calls other functions. Termi- nal symbols (for example, end, number, +, and −) are recognized by a lexical analyzer and nonter- minal symbols are recognized by the syntax analyzer functions, expr(), term(), and prim(). As soon as both operands of a (sub)expression are known, the expression is evaluated; in a real compiler, code could be generated at this point. For input, the parser uses a Token_stream that encapsulates the reading of characters and their composition into Tokens. That is, a Token_stream ‘‘tokenizes’’: it turns streams of characters, such as 123.45, into Tokens. A Token is a {kind-of-token,value} pair, such as {number,123.45}, where the 123.45 has been turned into a floating point value. The main parts of the parser need only to know the name of the Token_stream, ts, and how to get Tokens from it. To read the next Token, it calls ts.get(). To get the most recently read Token (the ‘‘current token’’), it calls ts.current(). In addition to providing tokenizing, the Token_stream hides the actual source of the characters. We’ll see that they can come directly from a user typing to cin, from a program command line, or from any other input stream (§10.2 .7). The definition of Token looks like this: enum class Kind : char { name, number, end, plus='+', minus='−', mul='∗', div='/’, print=';', assign='=', lp='(', rp=')' }; struct Token { Kind kind; string string_value; double number_value; }; Representing each token by the integer value of its character is convenient and efficient and can be a help to people using debuggers. This works as long as no character used as input has a value used as an enumerator – and no current character set I know of has a printing character with a single- digit integer value. The interface to Token_stream looks like this: class Token_stream { public: Token get(); // read and return next token const Token& current(); // most recently read token // ... }; The implementation is presented in §10.2 .2 . Each parser function takes a bool (§6.2 .2) argument, called get, indicating whether the function needs to call Token_stream::get() to get the next token. Each parser function evaluates ‘‘its’’
ptg10564057 244 Expressions Chapter 10 expression and returns the value. The function expr() handles addition and subtraction. It consists of a single loop that looks for terms to add or subtract: double expr(bool get) // add and subtract { double left = term(get); for (;;) { // ‘‘forever’’ switch (ts.current().kind) { case Kind::plus: left += term(true); break; case Kind::minus: left −= term(true); break; default: return left; } } } This function really does not do much itself. In a manner typical of higher-level functions in a large program, it calls other functions to do the work. The switch-statement (§2.2 .4, §9.4 .2) tests the value of its condition, which is supplied in paren- theses after the switch keyword, against a set of constants. The break-statements are used to exit the switch-statement. If the value tested does not match any case label, the default is chosen. The pro- grammer need not provide a default. Note that an expression such as 2−3+4 is evaluated as (2−3)+4, as specified in the grammar. The curious notation for(;;) is a way to specify an infinite loop; you could pronounce it ‘‘for- ever’’ (§9.5); while(true) is an alternative. The switch-statement is executed repeatedly until some- thing different from + and − is found, and then the return-statement in the default case is executed. The operators += and −= are used to handle the addition and subtraction; left=left+term(true) and left=left−term(true) could have been used without changing the meaning of the program. However, left+=term(true) and left−=term(true) are not only shorter but also express the intended operation directly. Each assignment operator is a separate lexical token, so a+=1;is a syntax error because of the space between the + and the =. C++ provides assignment operators for the binary operators: + − ∗ /%&|ˆ << >> so that the following assignment operators are possible: =+ =−= ∗= /=%=&=|= ˆ= <<= >>= The % is the modulo, or remainder, operator; &, |, and ˆ are the bitwise logical operators and, or, and exclusive or; << and >> are the left shift and right shift operators; §10.3 summarizes the operators and their meanings. For a binary operator @ applied to operands of built-in types, an expression x@=y means x=x@y, except that x is evaluated once only.
ptg10564057 Section 10.2 .1 The Parser 245 The function term() handles multiplication and division in the same way expr() handles addition and subtraction: double term(bool get) // multiply and divide { double left = prim(get); for (;;) { switch (ts.current().kind) { case Kind::mul: left ∗= prim(true); break; case Kind::div: if (auto d = prim(true)) { left /= d; break; } return error("divide by 0"); default: return left; } } } The result of dividing by zero is undefined and usually disastrous. We therefore test for 0 before dividing and call error() if we detect a zero divisor. The function error() is described in §10.2 .4 . The variable d is introduced into the program exactly where it is needed and initialized immedi- ately. The scope of a name introduced in a condition is the statement controlled by that condition, and the resulting value is the value of the condition (§9.4.3). Consequently, the division and assignment left/=d are done if and only if d is nonzero. The function prim() handling a primary is much like expr() and term(), except that because we are getting lower in the call hierarchy a bit of real work is being done and no loop is necessary: double prim(bool get) // handle primaries { if (get) ts.get(); // read next token switch (ts.current().kind) { case Kind::number: // floating-point constant { double v = ts.current().number_value; ts.get(); return v; } case Kind::name: { double& v = table[ts.current().string_value]; // find the corresponding if (ts.get().kind == Kind::assign) v = expr(true); // ’=’ seen: assignment return v; }
ptg10564057 246 Expressions Chapter 10 case Kind::minus: // unary minus return −prim(true); case Kind::lp: { auto e = expr(true); if (ts.current().kind != Kind::rp) return error("')' expected"); ts.get(); // eat ’)’ return e; } default: return error("primary expected"); } } When a Token that is a number (that is, an integer or floating-point literal) is seen, its value is placed in its number_value. Similarly, when a Token that is a name (however defined; see §10.2 .2 and §10.2 .3) is seen, its value is placed in its string_value. Note that prim() always reads one more Token than it uses to analyze its primary expression. The reason is that it must do that in some cases (e.g ., to see if a name is assigned to), so for consis- tency it must do it in all cases. In the cases where a parser function simply wants to move ahead to the next Token, it doesn’t use the return value from ts.get(). That’s fine because we can get the result from ts.current(). Had ignoring the return value of get() bothered me, I’d have either added a read() function that just updated current() without returning a value or explicitly ‘‘thrown away’’ the result: void(ts.get()). Before doing anything to a name, the calculator must first look ahead to see if it is being assigned to or simply read. In both cases, the symbol table is consulted. The symbol table is a map (§4.4 .3, §31.4.3): map<string,double> table; That is, when table is indexed by a string, the resulting value is the double corresponding to the string. For example, if the user enters radius = 6378.388; the calculator will reach case Kind::name and execute double& v = table["radius"]; // ... expr() calculates the value to be assigned ... v = 6378.388; The reference v is used to hold on to the double associated with radius while expr() calculates the value 6378.388 from the input characters. Chapter 14 and Chapter 15 discuss how to organize a program as a set of modules. However, with one exception, the declarations for this calculator example can be ordered so that everything is declared exactly once and before it is used. The exception is expr(), which calls term(), which calls prim(), which in turn calls expr(). This loop of calls must be broken somehow. A declaration double expr(bool); before the definition of prim() will do nicely.
ptg10564057 Section 10.2 .2 Input 247 10.2.2 Input Reading input is often the messiest part of a program. To communicate with a person, the program must cope with that person’s whims, conventions, and seemingly random errors. Trying to force the person to behave in a manner more suitable for the machine is often (rightly) considered offen- sive. The task of a low-level input routine is to read characters and compose higher-level tokens from them. These tokens are then the units of input for higher-level routines. Here, low-level input is done by ts.get(). Writing a low-level input routine need not be an everyday task. Many systems provide standard functions for this. First we need to see the complete definition of Token_stream: class Token_stream { public: Token_stream(istream& s) : ip{&s}, owns{false} { } Token_stream(istream∗ p) : ip{p}, owns{true} { } ̃Token_stream() { close(); } Token get(); // read and return next token Token& current(); // most recently read token void set_input(istream& s) { close(); ip = &s; owns=false; } void set_input(istream∗ p) { close(); ip = p; owns = true; } private: void close() { if (owns) delete ip; } istream∗ ip; // pointer to an input stream bool owns; // does the Token_stream own the istream? Token ct {Kind::end} ; // current token }; We initialize a Token_stream with an input stream (§4.3 .2, Chapter 38) from which it gets its char- acters. The Token_stream implements the convention that it owns (and eventually deletes; §3.2 .1 .2, §11.2) an istream passed as a pointer, but not an istream passed as a reference. This may be a bit elaborate for this simple program, but it is a useful and general technique for classes that hold a pointer to a resource requiring destruction. A Token_stream holds three values: a pointer to its input stream (ip), a Boolean (owns), indicat- ing ownership of the input stream, and the current token (ct). I gave ct a default value because it seemed sloppy not to. People should not call current() before get(), but if they do, they get a well-defined Token. I chose Kind::end as the initial value for ct so that a program that misuses current() will not get a value that wasn’t on the input stream. I present Token_stream::get() in two stages. First, I provide a deceptively simple version that imposes a burden on the user. Next, I modify it into a slightly less elegant, but much easier to use, version. The idea for get() is to read a character, use that character to decide what kind of token needs to be composed, read more characters when needed, and then return a Token representing the characters read.
ptg10564057 248 Expressions Chapter 10 The initial statements read the first non-whitespace character from ∗ip (the stream pointed to by ip) into ch and check that the read operation succeeded: Token Token_stream::get() { charch=0; ∗ip>>ch; switch (ch) { case 0: return ct={Kind::end}; // assign and return By default, operator >> skips whitespace (that is, spaces, tabs, newlines, etc.) and leaves the value of ch unchanged if the input operation failed. Consequently, ch==0 indicates end-of-input. Assignment is an operator, and the result of the assignment is the value of the variable assigned to. This allows me to assign the value Kind::end to curr_tok and return it in the same statement. Having a single statement rather than two is useful in maintenance. If the assignment and the return became separated in the code, a programmer might update the one and forget to update the other. Note also how the {}-list notation (§3.2 .1 .3, §11.3) is used on the right-hand side of an assign- ment. That is, it is an expression. I could have written that return-statement as: ct.kind = Kind::end; // assign return ct; // return However, I think that assigning a complete object {Kind::end} is clearer than dealing with individual members of ct. The {Kind::end} is equivalent to {Kind::end,0,0}. That’s good if we care about the last two members of the Token and not so good if we are worried about performance. Neither is the case here, but in general dealing with complete objects is clearer and less error-prone than manipu- lating data members individually. The cases below give examples of the other strategy. Consider some of the cases separately before considering the complete function. The expres- sion terminator, ';', the parentheses, and the operators are handled simply by returning their values: case ';': // end of expression; print case '∗': case '/': case '+': case '−': case '(': case ')': case '=': return ct={static_cast<Kind>(ch)}; The static_cast (§11.5 .2) is needed because there is no implicit conversion from char to Kind (§8.4 .1); only some characters correspond to Kind values, so we have to ‘‘certify’’ that in this case ch does. Numbers are handled like this: case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '.':
ptg10564057 Section 10.2 .2 Input 249 ip−>putback(ch); // put the first digit (or .) back into the input stream ∗ip >> ct.number_value; // read the number into ct ct.kind=Kind::number; return ct; Stacking case labels horizontally rather than vertically is generally not a good idea because this arrangement is harder to read. However, having one line for each digit is tedious. Because opera- tor >> is already defined for reading floating-point values into a double, the code is trivial. First the initial character (a digit or a dot) is put back into cin. Then, the floating-point value can be read into ct.number_value. If the token is not the end of input, an operator, a punctuation character, or a number, it must be a name. A name is handled similarly to a number: default: // name, name =, or error if (isalpha(ch)) { ip−>putback(ch); // put the first character back into the input stream ∗ip>>ct.string_value; // read the string into ct ct.kind=Kind::name; return ct; } Finally, we may simply have an error. The simple-minded, but reasonably effective way to deal with an error is the write call an error() function and then return a print token if error() returns: error("bad token"); return ct={Kind::print}; The standard-library function isalpha() (§36.2 .1) is used to avoid listing every character as a sepa- rate case label. Operator >> applied to a string (in this case, string_value) reads until it hits white- space. Consequently, a user must terminate a name by a space before an operator using the name as an operand. This is less than ideal, so we will return to this problem in §10.2 .3 . Here, finally, is the complete input function: Token Token_stream::get() { charch=0; ∗ip>>ch; switch (ch) { case 0: return ct={Kind::end}; // assign and return case ';': // end of expression; print case '∗': case '/': case '+': case '−': case '(': case ')': case '=': return ct=={static_cast<Kind>(ch)};
ptg10564057 250 Expressions Chapter 10 case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '.': ip−>putback(ch); // put the first digit (or .) back into the input stream ∗ip >> ct.number_value; // read number into ct ct.kind=Kind::number; return ct; default: // name, name =, or error if (isalpha(ch)) { ip−>putback(ch); // put the first character back into the input stream ∗ip>>ct.string_value; // read string into ct ct.kind=Kind::name; return ct; } error("bad token"); return ct={Kind::print}; } } The conversion of an operator to its Token value is trivial because the kind of an operator was defined as the integer value of the operator (§10.2 .1). 10.2.3 Low-Level Input Using the calculator as defined so far reveals a few inconveniences. It is tedious to remember to add a semicolon after an expression in order to get its value printed, and having a name terminated by whitespace only is a real nuisance. For example, x=7 is an identifier – rather than the identifier x followed by the operator = and the number 7. To get what we (usually) want, we would have to add whitespace after x: x=7. Both problems are solved by replacing the type-oriented default input operations in get() with code that reads individual characters. First, we’ll make a newline equivalent to the semicolon used to mark the end-of-expression: Token Token_stream::get() { char ch; do { // skip whitespace except ’\n’ if (!ip−>get(ch)) return ct={Kind::end}; } while (ch!='\n' && isspace(ch)); switch (ch) { case ';': case '\n': return ct={Kind::print}; Here, I use a do-statement; it is equivalent to a while-statement except that the controlled statement is always executed at least once. The call ip−>get(ch) reads a single character from the input stream ∗ip into ch. By default, get() does not skip whitespace the way >> does. The test if (!ip−>get(ch)) succeeds if no character can be read from cin; in this case, Kind::end is returned to terminate the calculator session. The operator ! (not) is used because get() returns true in case of success.
ptg10564057 Section 10.2 .3 Low-Level Input 251 The standard-library function isspace() provides the standard test for whitespace (§36.2 .1); isspace(c) returns a nonzero value if c is a whitespace character and zero otherwise. The test is implemented as a table lookup, so using isspace() is much faster than testing for the individual whitespace characters. Similar functions test if a character is a digit (isdigit()), a letter (isalpha()), or a digit or letter (isalnum()). After whitespace has been skipped, the next character is used to determine what kind of lexical token is coming. The problem caused by >> reading into a string until whitespace is encountered is solved by reading one character at a time until a character that is not a letter or a digit is found: default: // NAME, NAME=, or error if (isalpha(ch)) { string_value = ch; while (ip−>get(ch) && isalnum(ch)) string_value += ch; // append ch to end of string_value ip−>putback(ch); return ct={Kind::name}; } Fortunately, these two improvements could both be implemented by modifying a single local sec- tion of code. Constructing programs so that improvements can be implemented through local mod- ifications only is an important design aim. You might worry that adding characters to the end of a string one by one would be inefficient. It would be for very long strings, but all modern string implementations provide the ‘‘small string optimization’’ (§19.3.3). That means that handling the kind of strings we are likely to use as names in a calculator (or even in a compiler) doesn’t involve any inefficient operations. In particular, using a short string doesn’t require any use of free store. The maximum number of characters for a short string is implementation-dependent, but 14 would be a good guess. 10.2.4 Error Handling It is always important to detect and report errors. However, for this program, a simple error han- dling strategy suffices. The error() function simply counts the errors, writes out an error message, and returns: int no_of_errors; double error(const string& s) { no_of_errors++; cerr << "error: " << s << '\n'; return 1; } The stream cerr is an unbuffered output stream usually used to report errors (§38.1). The reason for returning a value is that errors typically occur in the middle of the evaluation of an expression, so we should either abort that evaluation entirely or return a value that is unlikely to cause subsequent errors. The latter is adequate for this simple calculator. Had Token_stream::get()
ptg10564057 252 Expressions Chapter 10 kept track of the line numbers, error() could have informed the user approximately where the error occurred. This would be useful when the calculator is used noninteractively. A more stylized and general error-handling strategy would separate error detection from error recovery. This can be implemented using exceptions (see §2.4.3 .1, Chapter 13), but what we have here is quite suitable for a 180-line calculator. 10.2.5 The Driver With all the pieces of the program in place, we need only a driver to start things. I decided on two functions: main() to do setup and error reporting and calculate() to handle the actual calculation: Token_stream ts {cin}; // use input from cin void calculate() { for (;;) { ts.get(); if (ts.current().kind == Kind::end) break; if (ts.current().kind == Kind::print) continue; cout << expr(false) << '\n'; } } int main() { table["pi"] = 3.1415926535897932385; // insert predefined names table["e"] = 2.7182818284590452354; calculate(); return no_of_errors; } Conventionally, main() returns zero if the program terminates normally and nonzero otherwise (§2.2 .1). Returning the number of errors accomplishes this nicely. As it happens, the only initial- ization needed is to insert the predefined names into the symbol table. The primary task of the main loop (in calculate()) is to read expressions and write out the answer. This is achieved by the line: cout << expr(false) << '\n'; The argument false tells expr() that it does not need to call ts.get() to read a token on which to work. Testing for Kind::end ensures that the loop is correctly exited when ts.get() encounters an input error or an end-of-file. A break-statement exits its nearest enclosing switch-statement or loop (§9.5). Testing for Kind::print (that is, for '\n' and ';') relieves expr() of the responsibility for han- dling empty expressions. A continue-statement is equivalent to going to the very end of a loop.
ptg10564057 Section 10.2 .6 Headers 253 10.2.6 Headers The calculator uses standard-library facilities. Therefore, appropriate headers must be #includedto complete the program: #include<iostream> // I/O #include<string> // strings #include<map> // map #include<cctype> // isalpha(), etc. All of these headers provide facilities in the std namespace, so to use the names they provide we must either use explicit qualification with std:: or bring the names into the global namespace by using namespace std; To avoid confusing the discussion of expressions with modularity issues, I did the latter. Chapter 14 and Chapter 15 discuss ways of organizing this calculator into modules using namespaces and how to organize it into source files. 10.2.7 Command-Line Arguments After the program was written and tested, I found it a bother to first start the program, then type the expressions, and finally quit. My most common use was to evaluate a single expression. If that expression could be presented as a command-line argument, a few keystrokes could be avoided. A program starts by calling main() (§2.2 .1, §15.4). When this is done, main() is given two argu- ments specifying the number of arguments, conventionally called argc, and an array of arguments, conventionally called argv. The arguments are C-style character strings (§2.2.5, §7.3), so the type of argv is char∗[argc+1]. The name of the program (as it occurs on the command line) is passed as argv[0],soargc is always at least 1. The list of arguments is zero-terminated; that is, argv[argc]==0. For example, for the command dc 150/1.1934 the arguments have these values: 2 argc: argv: 0 "dc" "150/1.1934" Because the conventions for calling main() are shared with C, C-style arrays and strings are used. The idea is to read from the command string in the same way that we read from the input stream. A stream that reads from a string is unsurprisingly called an istringstream (§38.2 .2). So to calculate expressions presented on the command line, we simply have to get our Token_stream to read from an appropriate istringstream:
ptg10564057 254 Expressions Chapter 10 Token_stream ts {cin}; int main(int argc, char∗ argv[]) { switch (argc) { case 1: // read from standard input break; case 2: // read from argument string ts.set_input(new istringstream{argv[1]}); break; default: error("too many arguments"); return 1; } table["pi"] = 3.1415926535897932385; // insert predefined names table["e"] = 2.7182818284590452354; calculate(); return no_of_errors; } To use an istringstream, include <sstream>. It would be easy to modify main() to accept several command-line arguments, but this does not appear to be necessary, especially as several expressions can be passed as a single argument: dc "rate=1.1934;150/rate;19.75/rate;217/rate" I use quotes because ; is the command separator on my UNIX systems. Other systems have differ- ent conventions for supplying arguments to a program on startup. Simple as they are, argc and argv are still a source of minor, yet annoying, bugs. To avoid those and especially to make it easier to pass around the program arguments, I tend to use a simple func- tion to create a vector<string>: vector<string> arguments(int argc, char∗ argv[]) { vector<string> res; for (int i = 0; i!=argc; ++i) res.push_back(argv[i]); return res; } More elaborate argument parsing functions are not uncommon. 10.2.8 A Note on Style To programmers unacquainted with associative arrays, the use of the standard-library map as the symbol table seems almost like cheating. It is not. The standard library and other libraries are meant to be used. Often, a library has received more care in its design and implementation than a
ptg10564057 Section 10.2 .8 A Note on Style 255 programmer could afford for a handcrafted piece of code to be used in just one program. Looking at the code for the calculator, especially at the first version, we can see that there isn’t much traditional C-style, low-level code presented. Many of the traditional tricky details have been replaced by uses of standard-library classes such as ostream, string, and map (§4.3 .1, §4.2, §4.4 .3, §31.4, Chapter 36, Chapter 38). Note the relative scarcity of loops, arithmetic, and assignments. This is the way things ought to be in code that doesn’t manipulate hardware directly or implement low-level abstractions. 10.3 Operator Summary This section presents a summary of expressions and some examples. Each operator is followed by one or more names commonly used for it and an example of its use. In these tables: •A name is an identifier (e.g ., sum and map), an operator name (e.g ., operator int, operator+, and operator"" km), or the name of a template specialization (e.g ., sort<Record> and array<int,10>), possibly qualified using :: (e.g ., std::vector and vector<T>::operator[]). •A class-name is the name of a class (including decltype(expr) where expr denotes a class). •A member is a member name (including the name of a destructor or a member template). •A n object is an expression yielding a class object. •Apointer is an expression yielding a pointer (including this and an object of that type that supports the pointer operation). •A n expr is an expression, including a literal (e.g ., 17, "mouse", and true) •A n expr-list is a (possibly empty) list of expressions. •A n lvalue is an expression denoting a modifiable object (§6.4 .1). •Atype can be a fully general type name (with ∗, (), etc.) only when it appears in parenthe- ses; elsewhere, there are restrictions (§iso.A). •A lambda-declarator is a (possibly empty, comma-separated) list of parameters optionally followed by the mutable specifier, optionally followed by a noexcept specifier, optionally fol- lowed by a return type (§11.4). •A capture-list is a (possibly empty) list specifying context dependencies (§11.4). •A stmt-list is a (possibly empty) list of statements (§2.2.4, Chapter 9). The syntax of expressions is independent of operand types. The meanings presented here apply when the operands are of built-in types (§6.2.1). In addition, you can define meanings for operators applied to operands of user-defined types (§2.3, Chapter 18). A table can only approximate the rules of the grammar. For details, see §iso.5 and §iso.A. Operator Summary (continues) (§iso.5 .1) Parenthesized expression ( expr ) Lambda [ capture-list ] lambda-declarator { stmt-List } §11.4 Scope resolution class-name :: member §16.2 .3 Scope resolution namespace-name :: member §14.2 .1 Global :: name §14.2 .1 Each box holds operators with the same precedence. Operators in higher boxes have higher prece- dence. For example, N::x.m means (N::m).m rather than the illegal N::(x.m).
ptg10564057 256 Expressions Chapter 10 Operator Summary (continued, continues) Member selection object . member §16.2 .3 Member selection pointer −> member §16.2 .3 Subscripting pointer [ expr ] §7.3 Function call expr ( expr-list ) §12.2 Value construction type { expr-list } §11.3 .2 Function-style type conversion type ( expr-list ) §11.5 .4 Post increment lvalue ++ §11.1 .4 Post decrement lvalue −− §11.1 .4 Type identification typeid ( type ) §22.5 Run-time type identification typeid ( expr ) §22.5 Run-time checked conversion dynamic_cast < type >(expr ) §22.2 .1 Compile-time checked conversion static_cast < type >(expr ) §11.5 .2 Unchecked conversion reinterpret_cast < type >(expr ) §11.5 .2 const conversion const_cast < type >(expr ) §11.5 .2 Size of object sizeof expr §6.2 .8 Size of type sizeof ( type ) §6.2 .8 Size of parameter pack sizeof... name §28.6 .2 Alignment of type alignof ( type ) §6.2 .9 Pre increment ++ lvalue §11.1 .4 Pre decrement −− lvalue §11.1 .4 Complement ̃ expr §11.1 .2 Not ! expr §11.1 .1 Unary minus − expr §2.2 .2 Unary plus + expr §2.2 .2 Address of & lvalue §7.2 Dereference ∗ expr §7.2 Create (allocate) new type §11.2 Create (allocate and initialize) new type ( expr-list ) §11.2 Create (allocate and initialize) new type { expr-list } §11.2 Create (place) new ( expr-list ) type §11.2 .4 Create (place and initialize) new ( expr-list ) type ( expr-list ) §11.2 .4 Create (place and initialize) new ( expr-list ) type { expr-list } §11.2 .4 Destroy (deallocate) delete pointer §11.2 Destroy array delete [] pointer §11.2 .2 Can expression throw? noexcept ( expr ) §13.5 .1 .2 Cast (type conversion) ( type ) expr §11.5 .3 Member selection object .∗ pointer-to-member §20.6 Member selection pointer −>∗ pointer-to-member §20.6 For example, postfix ++ has higher precedence than unary ∗,so∗p++ means ∗(p++), not (∗p)++.
ptg10564057 Section 10.3 Operator Summary 257 Operator Summary (continued) Multiply expr ∗ expr §10.2 .1 Divide expr / expr §10.2 .1 Modulo (remainder) expr % expr §10.2 .1 Add (plus) expr + expr §10.2 .1 Subtract (minus) expr − expr §10.2 .1 Shift left expr << expr §11.1 .2 Shift right expr >> expr §11.1 .2 Less than expr < expr §2.2 .2 Less than or equal expr <= expr §2.2 .2 Greater than expr > expr §2.2 .2 Greater than or equal expr >= expr §2.2 .2 Equal expr == expr §2.2 .2 Not equal expr != expr §2.2 .2 Bitwise and expr & expr §11.1 .2 Bitwise exclusive-or expr ˆ expr §11.1 .2 Bitwise inclusive-or expr | expr §11.1 .2 Logical and expr && expr §11.1 .1 Logical inclusive or expr || expr §11.1 .1 Conditional expression expr ? expr : expr §11.1 .3 List { expr-list } §11.3 Throw exception throw expr §13.5 Simple assignment lvalue = expr §10.2 .1 Multiply and assign lvalue ∗= expr §10.2 .1 Divide and assign lvalue /= expr §10.2 .1 Modulo and assign lvalue %= expr §10.2 .1 Add and assign lvalue += expr §10.2 .1 Subtract and assign lvalue −= expr §10.2 .1 Shift left and assign lvalue <<= expr §10.2 .1 Shift right and assign lvalue >>= expr §10.2 .1 Bitwise and and assign lvalue &= expr §10.2 .1 Bitwise inclusive-or and assign lvalue |= expr §10.2 .1 Bitwise exclusive-or and assign lvalue ˆ= expr §10.2 .1 comma (sequencing) expr , expr §10.3 .2 For example: a+b∗c means a+(b∗c) rather than (a+b)∗c because ∗ has higher precedence than +. Unary operators and assignment operators are right-associative; all others are left-associative. For example, a=b=c means a=(b=c) whereas a+b+c means (a+b)+c. A few grammar rules cannot be expressed in terms of precedence (also known as binding strength) and associativity. For example, a=b<c?d=e:f=g means a=((b<c)?(d=e):(f=g)), but you need to look at the grammar (§iso.A) to determine that.
ptg10564057 258 Expressions Chapter 10 Before applying the grammar rules, lexical tokens are composed from characters. The longest possible sequence of characters is chosen to make a token. For example, && is a single operator, rather than two & operators, and a+++1 means (a ++) + 1. This is sometimes called the Max Munch rule. Token Summary (§iso.2 .7) Token Class Examples Reference Identifier vector, foo_bar, x3 §6.3 .3 Keyword int, for, virtual §6.3 .3 .1 Character literal ’x’, \n’, ’U’\UFADEFADE’ §6.2 .3 .2 Integer literal 12, 012, 0x12 §6.2 .4 .1 Floating-point literal 1.2, 1.2e−3, 1.2L §6.2 .5 .1 String literal "Hello!", R"("World"!)" §7.3 .2 Operator +=, %, << §10.3 Punctuation ;, ,, {,},(,) Preprocessor notation #, ## §12.6 Whitespace characters (e.g ., space, tab, and newline) can be token separators (e.g ., int count is a keyword followed by an identifier, rather than intcount) but are otherwise ignored. Some characters from the basic source character set (§6.1 .2), such as |, are not convenient to type on some keywords. Also, some programmers find it odd to use of symbols, such as && and ̃, for basic logical operations. Consequently, a set of alternative representation are provided as keywords: Alternative Representation (§iso.2 .12) and and_eq bitand bitor compl not not_eq or or_eq xor xor_eq & &= & | ̃ ! != | |= ˆ ˆ= For example boolb= not(xory)andz; int x4 = ̃ (x1 bitor x2) bitand x3; is equivalent to boolb=!(x||y)&&z; intx4= ̃(x1|x2)&x3; Note that and= is not equivalent to &=; if you prefer keywords, you must write and_eq. 10.3.1 Results The result types of arithmetic operators are determined by a set of rules known as ‘‘the usual arith- metic conversions’’ (§10.5 .3). The overall aim is to produce a result of the ‘‘largest’’ operand type. For example, if a binary operator has a floating-point operand, the computation is done using float- ing-point arithmetic and the result is a floating-point value. Similarly, if it has a long operand, the computation is done using long integer arithmetic, and the result is a long. Operands that are smaller than an int (such as bool and char) are converted to int before the operator is applied.
ptg10564057 Section 10.3 .1 Results 259 The relational operators, ==, <=, etc., produce Boolean results. The meaning and result type of user-defined operators are determined by their declarations (§18.2). Where logically feasible, the result of an operator that takes an lvalue operand is an lvalue denoting that lvalue operand. For example: void f(int x, int y) { intj=x=y; // the value of x=y is the value of x after the assignment int∗ p = &++x; //ppointstox int∗ q = &(x++); // error: x++ is not an lvalue (it is not the value stored in x) int∗ p2 = &(x>y?x:y); // address of the int with the larger value int& r = (x<y)?x:1; // error: 1 is not an lvalue } If both the second and third operands of ?: are lvalues and have the same type, the result is of that type and is an lvalue. Preserving lvalues in this way allows greater flexibility in using operators. This is particularly useful when writing code that needs to work uniformly and efficiently with both built-in and user-defined types (e.g ., when writing templates or programs that generate C++ code). The result of sizeof is of an unsigned integral type called size_t defined in <cstddef>. The result of pointer subtraction is of a signed integral type called ptrdiff_t defined in <cstddef>. Implementations do not have to check for arithmetic overflow and hardly any do. For example: void f() { inti=1; while (0 < i) ++i; cout << "i has become negative!" << i << '\n'; } This will (eventually) try to increase i past the largest integer. What happens then is undefined, but typically the value ‘‘wraps around’’ to a negative number (on my machine −2147483648). Similarly, the effect of dividing by zero is undefined, but doing so usually causes abrupt termination of the program. In particular, underflow, overflow, and division by zero do not throw standard exceptions (§30.4.1 .1). 10.3.2 Order of Evaluation The order of evaluation of subexpressions within an expression is undefined. In particular, you can- not assume that the expression is evaluated left-to-right. For example: int x = f(2)+g(3); // undefined whether f() or g() is called first Better code can be generated in the absence of restrictions on expression evaluation order. How- ever, the absence of restrictions on evaluation order can lead to undefined results. For example: inti=1; v[i] = i++; // undefined result The assignment may be evaluated as either v[1]=1 or v[2]=1 or may cause some even stranger behav- ior. Compilers can warn about such ambiguities. Unfortunately, most do not, so be careful not to write an expression that reads or writes an object more than once, unless it does so using a single
ptg10564057 260 Expressions Chapter 10 operator that makes it well defined, such as ++ and +=, or explicitly express sequencing using , (comma), &&,or||. The operators , (comma), && (logical and), and || (logical or) guarantee that their left-hand oper- and is evaluated before their right-hand operand. For example, b=(a=2,a+1) assigns 3 to b. Exam- ples of the use of || and && can be found in §10.3 .3 . For built-in types, the second operand of && is evaluated only if its first operand is true, and the second operand of || is evaluated only if its first op- erand is false; this is sometimes called short-circuit evaluation. Note that the sequencing operator , (comma) is logically different from the comma used to separate arguments in a function call. For example: f1(v[i],i++); // two arguments f2( (v[i],i++) ); // one argument The call of f1 has two arguments, v[i] and i++, and the order of evaluation of the argument expres- sions is undefined. So it should be avoided. Order dependence of argument expressions is very poor style and has undefined behavior. The call of f2 has only one argument, the comma expression (v[i],i++), which is equivalent to i++. That is confusing, so that too should be avoided. Parentheses can be used to force grouping. For example, a∗b/c means (a∗b)/c, so parentheses must be used to get a∗(b/c); a∗(b/c) may be evaluated as (a∗b)/c only if the user cannot tell the differ- ence. In particular, for many floating-point computations a∗(b/c) and (a∗b)/c are significantly differ- ent, so a compiler will evaluate such expressions exactly as written. 10.3.3 Operator Precedence Precedence levels and associativity rules reflect the most common usage. For example: if (i<=0 || max<i) // ... means ‘‘if i is less than or equal to 0 or if max is less than i.’’ That is, it is equivalent to if ( (i<=0) || (max<i) ) // ... and not the legal but nonsensical if (i <= (0||max) < i) // ... However, parentheses should be used whenever a programmer is in doubt about those rules. Use of parentheses becomes more common as the subexpressions become more complicated, but compli- cated subexpressions are a source of errors. Therefore, if you start feeling the need for parentheses, you might consider breaking up the expression by using an extra variable. There are cases when the operator precedence does not result in the ‘‘obvious’’ interpretation. For example: if (i&mask == 0) // oops! == expression as operand for & This does not apply a mask to i and then test if the result is zero. Because == has higher precedence than &, the expression is interpreted as i&(mask==0). Fortunately, it is easy enough for a compiler to warn about most such mistakes. In this case, parentheses are important: if ((i&mask) == 0) // ... It is worth noting that the following does not work the way a mathematician might expect:
ptg10564057 Section 10.3 .3 Operator Precedence 261 if(0<=x<=99)//... This is legal, but it is interpreted as (0<=x)<=99, where the result of the first comparison is either true or false. This Boolean value is then implicitly converted to 1 or 0, which is then compared to 99, yielding true. To test whether x is in the range 0..99, we might use if (0<=x && x<=99) // ... A common mistake for novices is to use = (assignment) instead of == (equals) in a condition: if (a = 7) // oops! constant assignment in condition This is natural because = means ‘‘equals’’ in many languages. Again, it is easy for a compiler to warn about most such mistakes – and many do. I do not recommend warping your style to com- pensate for compilers with weak warnings. In particular, I don’t consider this style worthwhile: if (7 == a) // try to protect against misuse of =; not recommended 10.3.4 Temporary Objects Often, the compiler must introduce an object to hold an intermediate result of an expression. For example, for v=x+y∗z the result of y∗z has to be put somewhere before it is added to x. For built-in types, this is all handled so that a temporary object (often referred to as just a temporary) is invisi- ble to the user. However, for a user-defined type that holds a resource knowing the lifetime of a temporary can be important. Unless bound to a reference or used to initialize a named object, a temporary object is destroyed at the end of the full expression in which it was created. A full expression is an expression that is not a subexpression of some other expression. The standard-library string has a member c_str() (§36.3) that returns a C-style pointer to a zero- terminated array of characters (§2.2.5, §43.4). Also, the operator + is defined to mean string con- catenation. These are useful facilities for strings. However, in combination they can cause obscure problems. For example: void f(string& s1, string& s2, string& s3) { const char∗ cs = (s1+s2).c _str(); cout << cs; if (strlen(cs=(s2+s3).c_str())<8 && cs[0]=='a') { // cs used here } } Probably, your first reaction is ‘‘But don’t do that!’’ and I agree. However, such code does get writ- ten, so it is worth knowing how it is interpreted. A temporary string object is created to hold s1+s2. Next, a pointer to a C-style string is extracted from that object. Then – at the end of the expression – the temporary object is deleted. However, the C-style string returned by c_str() was allocated as part of the temporary object holding s1+s2, and that storage is not guaranteed to exist after that temporary is destroyed. Consequently, cs points to deallocated storage. The output operation cout<<cs might work as expected, but that would be sheer luck. A compiler can detect and warn against many variants of this problem.
ptg10564057 262 Expressions Chapter 10 The problem with the if-statement is a bit more subtle. The condition will work as expected because the full expression in which the temporary holding s2+s3 is created is the condition itself. However, that temporary is destroyed before the controlled statement is entered, so any use of cs there is not guaranteed to work. Please note that in this case, as in many others, the problems with temporaries arose from using a high-level data type in a low-level way. A cleaner programming style yields a more understand- able program fragment and avoids the problems with temporaries completely. For example: void f(string& s1, string& s2, string& s3) { cout << s1+s2; string s = s2+s3; if (s.length()<8 && s[0]=='a') { // use s here } } A temporary can be used as an initializer for a const reference or a named object. For example: void g(const string&, const string&); void h(string& s1, string& s2) { const string& s = s1+s2; string ss = s1+s2; g(s,ss); // we can use s and ss here } This is fine. The temporary is destroyed when ‘‘its’’ reference or named object goes out of scope. Remember that returning a reference to a local variable is an error (§12.1.4) and that a temporary object cannot be bound to a non-const lvalue reference (§7.7). A temporary object can also be created explicitly in an expression by invoking a constructor (§11.5.1). For example: void f(Shape& s, int n, char ch) { s.move(string{n,ch}); // construct a string with n copies of ch to pass to Shape::move() // ... } Such temporaries are destroyed in exactly the same way as the implicitly generated temporaries. 10.4 Constant Expressions C++ offers two related meanings of ‘‘constant’’: • constexpr: Evaluate at compile time (§2.2 .3). • const: Do not modify in this scope (§2.2 .3, §7.5). Basically, constexpr’s role is to enable and ensure compile-time evaluation, whereas const’s
ptg10564057 Section 10.4 Constant Expressions 263 primary role is to specify immutability in interfaces. This section is primarily concerned with the first role: compile-time evaluation. A constant expression is an expression that a compiler can evaluate. It cannot use values that are not known at compile time and it cannot have side effects. Ultimately, a constant expression must start out with an integral value (§6.2 .1), a floating-point value (§6.2 .5), or an enumerator (§8.4), and we can combine those using operators and constexpr functions that in turn produce val- ues. In addition, some addresses can be used in some forms of constant expressions. For simplic- ity, I discuss those separately in §10.4 .5 . There are a variety of reasons why someone might want a named constant rather than a literal or a value stored in a variable: [1] Named constants make the code easier to understand and maintain. [2] A variable might be changed (so we have to be more careful in our reasoning than for a constant). [3] The language requires constant expressions for array sizes, case labels, and template value arguments. [4] Embedded systems programmers like to put immutable data into read-only memory because read-only memory is cheaper than dynamic memory (in terms of cost and energy consumption), and often more plentiful. Also, data in read-only memory is immune to most system crashes. [5] If initialization is done at compile time, there can be no data races on that object in a multi-threaded system. [6] Sometimes, evaluating something once (at compile time) gives significantly better perfor- mance than doing so a million times at run time. Note that reasons [1], [2], [5], and (partly) [4] are logical. We don’t just use constant expressions because of an obsession with performance. Often, the reason is that a constant expression is a more direct representation of our system requirements. As part of the definition of a data item (here, I deliberately avoid the word ‘‘variable’’), constexpr expresses the need for compile-time evaluation. If the initializer for a constexpr can’t be evaluated at compile time, the compiler will give an error. For example: intx1=7; constexpr int x2 = 7; constexpr int x3 = x1; // error: initializer is not a constant expression constexpr int x4 = x2; // OK void f() { constexpr int y3 = x1; // error: initializer is not a constant expression constexpr int y4 = x2; // OK // ... } A clever compiler could deduce that the value of x1 in the initializer for x3 was 7. However, we prefer not to rely on degrees of cleverness in compilers. In a large program, determining the values of variables at compile time is typically either very difficult or impossible.
ptg10564057 264 Expressions Chapter 10 The expressive power of constant expressions is great. We can use integer, floating-point, and enumeration values. We can use any operator that doesn’t modify state (e.g ., +, ?:, and [], but not = or ++). We can use constexpr functions (§12.1 .6) and literal types (§10.4.3) to provide a significant level of type safety and expressive power. It is almost unfair to compare this to what is commonly done with macros (§12.6). The conditional-expression operator ?: is the means of selection in a constant expression. For example, we can compute an integer square root at compile time: constexpr int isqrt_helper(int sq, int d, int a) { return sq <= a ? isqrt_helper(sq+d,d+2,a) : d; } constexpr int isqrt(int x) { return isqrt_helper(1,3,x)/2 − 1; } constexpr int s1 = isqrt(9); // s1 becomes 3 constexpr int s2 = isqrt(1234); The condition of a ?: is evaluated and then the selected alternative is evaluated. The alternative not selected is not evaluated and might even not be a constant expression. Similarly, operands of && and || that are not evaluated need not be constant expressions. This feature is primarily useful in constexpr functions that are sometimes used as constant expressions and sometimes not. 10.4.1 Symbolic Constants The most important single use of constants (constexpr or const values) is simply to provide sym- bolic names for values. Symbolic names should be used systematically to avoid ‘‘magic numbers’’ in code. Literal values scattered freely around in code is one of the nastiest maintenance hazards. If a numeric constant, such as an array bound, is repeated in code, it becomes hard to revise that code because every occurrence of that constant must be changed to update the code correctly. Using a symbolic name instead localizes information. Usually, a numeric constant represents an assumption about the program. For example, 4 may represent the number of bytes in an integer, 128 the number of characters needed to buffer input, and 6.24 the exchange factor between Danish kroner and U.S . dollars. Left as numeric constants in the code, these values are hard for a main- tainer to spot and understand. Also, many such values need to change over time. Often, such numeric values go unnoticed and become errors when a program is ported or when some other change violates the assumptions they represent. Representing assumptions as well-commented named (symbolic) constants minimizes such maintenance problems. 10.4.2 consts in Constant Expressions A const is primarily used to express interfaces (§7.5). However, const can also be used to express constant values. For example:
ptg10564057 Section 10.4 .2 consts in Constant Expressions 265 constintx=7; const string s = "asdf"; const int y = sqrt(x); A const initialized with a constant expression can be used in a constant expression. A const differs from a constexpr in that it can be initialized by something that is not a constant expression; in that case, the const cannot be used as a constant expression. For example: constexpr int xx = x; // OK constexpr string ss = s; // error: s is not a constant expression constexpr int yy = y; // error: sqrt(x) is not a constant expression The reasons for the errors are that string is not a literal type (§10.4 .3) and sqrt() is not a constexpr function (§12.1 .6). Usually, constexpr is a better choice than const for defining simple constants, but constexpr is new in C++11, so older code tends to use const. In many cases, enumerators (§8.4) are another alternative to consts. 10.4.3 Literal Types A sufficiently simple user-defined type can be used in a constant expression. For example: struct Point { int x,y,z; constexpr Point up(int d) { return {x,y,z+d}; } constexpr Point move(int dx, int dy) { return {x+dx,y+dy}; } // ... }; A class with a constexpr constructor is called a literal type. To be simple enough to be constexpr,a constructor must have an empty body and all members must be initialized by potentially constant expressions. For example: constexpr Point origo {0,0}; constexpr int z = origo.x; constexpr Point a[] = { origo, Point{1,1}, Point{2,2}, origo.move(3,3) }; constexpr int x = a[1].x; // x becomes 1 constexpr Point xy{0,sqrt(2)}; // error: sqrt(2) is not a constant expression Note that we can have constexpr arrays and also access array elements and object members. Naturally, we can define constexpr functions to take arguments of literal types. For example: constexpr int square(int x) { return x∗x; }
ptg10564057 266 Expressions Chapter 10 constexpr int radial_distance(Point p) { return isqrt(square(p.x)+square(p.y)+square(p.z)); } constexpr Point p1 {10,20,30}; // the default constructor is constexpr constexpr p2 {p1.up(20)}; // Point::up() is constexpr constexpr int dist = radial_distance(p2); I used int rather than double just because I didn’t have a constexpr floating-point square root func- tion handy. For a member function constexpr implies const, so I did not have to write: constexpr Point move(int dx, int dy) const { return {x+dx,y+dy}; } 10.4.4 Reference Arguments When working with constexpr, the key thing to remember is that constexpr is all about values. There are no objects that can change values or side effects here: constexpr provides a miniature compile-time functional programming language. That said, you might guess that constexpr cannot deal with references, but that’s only partially true because const references refer to values and can therefore be used. Consider the specialization of the general complex<T> to a complex<double> from the standard library: template<> class complex<double> { public: constexpr complex(double re = 0.0, double im = 0.0); constexpr complex(const complex<float>&); explicit constexpr complex(const complex<long double>&); constexpr double real(); // read the real part void real(double); // set the real part constexpr double imag(); // read the imaginary part void imag(double); // set the imaginary part complex<double>& operator= (double); complex<double>& operator+=(double); // ... }; Obviously, operations, such as = and +=, that modify an object cannot be constexpr. Conversely, operations that simply read an object, such as real() and imag(), can be constexpr and be evaluated at compile time given a constant expression. The interesting member is the template constructor from another complex type. Consider: constexpr complex<float> z1 {1,2}; // note: <float> not <double> constexpr double re = z1.real(); constexpr double im = z1.imag(); constexpr complex<double> z2 {re,im}; // z2 becomes a copy of z1 constexpr complex<double> z3 {z1}; // z3 becomes a copy of z1
ptg10564057 Section 10.4 .4 Reference Arguments 267 The copy constructor works because the compiler recognizes that the reference (the const com- plex<float>&) refers to a constant value and we just use that value (rather than trying anything advanced or silly with references or pointers). Literal types allow for type-rich compile-time programming. Traditionally, C++ compile-time evaluation has been restricted to using integer values (and without functions). This has resulted in code that was unnecessarily complicated and error-prone, as people encoded every kind of informa- tion as integers. Some uses of template metaprogramming (Chapter 28) are examples of that. Other programmers have simply preferred run-time evaluation to avoid the difficulties of writing in an impoverished language. 10.4.5 Address Constant Expressions The address of a statically allocated object (§6.4 .2), such as a global variable, is a constant. How- ever, its value is assigned by the linker, rather than the compiler, so the compiler cannot know the value of such an address constant. That limits the range of constant expressions of pointer and ref- erence type. For example: constexpr const char∗ p1 = "asdf"; constexpr const char∗ p2 = p1; // OK constexpr const char∗ p2 = p1+2; // error: the compiler does not know the value of p1 constexpr char c = p1[2]; // OK, c==’d’; the compiler knows the value pointed to by p1 10.5 Implicit Type Conversion Integral and floating-point types (§6.2.1) can be mixed freely in assignments and expressions. Wherever possible, values are converted so as not to lose information. Unfortunately, some value- destroying (‘‘narrowing’’) conversions are also performed implicitly. A conversion is value-pre- serving if you can convert a value and then convert the result back to its original type and get the original value. If a conversion cannot do that, it is a narrowing conversion (§10.5.2 .6). This sec- tion provides a description of conversion rules, conversion problems, and their resolution. 10.5.1 Promotions The implicit conversions that preserve values are commonly referred to as promotions. Before an arithmetic operation is performed, integral promotion is used to create ints out of shorter integer types. Similarly, floating-point promotion is used to create doubles out of floats. Note that these promotions will not promote to long (unless the operand is a char16_t, char32_t, wchar_t, or a plain enumeration that is already larger than an int)orlong double. This reflects the original purpose of these promotions in C: to bring operands to the ‘‘natural’’ size for arithmetic operations. The integral promotions are: •A char, signed char, unsigned char, short int,orunsigned short int is converted to an int if int can represent all the values of the source type; otherwise, it is converted to an unsigned int. •A char16_t, char32_t, wchar_t (§6.2 .3), or a plain enumeration type (§8.4.2) is converted to the first of the following types that can represent all the values of its underlying type: int, unsigned int, long, unsigned long,orunsigned long long.
ptg10564057 268 Expressions Chapter 10 • A bit-field (§8.2.7) is converted to an int if int can represent all the values of the bit-field; otherwise, it is converted to unsigned int if unsigned int can represent all the values of the bit-field. Otherwise, no integral promotion applies to it. •Abool is converted to an int; false becomes 0 and true becomes 1. Promotions are used as part of the usual arithmetic conversions (§10.5 .3). 10.5.2 Conversions The fundamental types can be implicitly converted into each other in a bewildering number of ways (§iso.4). In my opinion, too many conversions are allowed. For example: void f(double d) { charc=d; // beware: double-precision floating-point to char conversion } When writing code, you should always aim to avoid undefined behavior and conversions that qui- etly throw away information (‘‘narrowing conversions’’). A compiler can warn about many questionable conversions. Fortunately, many compilers do. The {}-initializer syntax prevents narrowing (§6.3.5). For example: void f(double d) { char c {d}; // error: double-precision floating-point to char conversion } If potentially narrowing conversions are unavoidable, consider using some form of run-time checked conversion function, such as narrow_cast<>() (§11.5). 10.5 .2 .1 Integral Conversions An integer can be converted to another integer type. A plain enumeration value can be converted to an integer type (§8.4 .2) . If the destination type is unsigned, the resulting value is simply as many bits from the source as will fit in the destination (high-order bits are thrown away if necessary). More precisely, the result is the least unsigned integer congruent to the source integer modulo 2 to the nth, where n is the number of bits used to represent the unsigned type. For example: unsigned char uc = 1023;// binary 1111111111: uc becomes binary 11111111, that is, 255 If the destination type is signed, the value is unchanged if it can be represented in the destination type; otherwise, the value is implementation-defined: signed char sc = 1023; // implementation-defined Plausible results are 127 and −1 (§6.2 .3). A Boolean or plain enumeration value can be implicitly converted to its integer equivalent (§6.2 .2, §8.4).
ptg10564057 Section 10.5 .2 .2 Floating-Point Conversions 269 10.5 .2 .2 Floating-Point Conversions A floating-point value can be converted to another floating-point type. If the source value can be exactly represented in the destination type, the result is the original numeric value. If the source value is between two adjacent destination values, the result is one of those values. Otherwise, the behavior is undefined. For example: float f = FLT_MAX; // largest float value double d = f; //OK:d==f double d2 = DBL_MAX; // largest double value float f2 = d2; // undefined if FLT_MAX<DBL_MAX long double ld = d2; //OK:ld=d3 long double ld2 = numeric_limits<long double>::max(); double d3 = ld2; // undefined if sizeof(long double)>sizeof(double) DBL_MAX and FLT_MAX are defined in <climits>; numeric_limits is defined in <limits> (§40.2). 10.5 .2 .3 Pointer and Reference Conversions Any pointer to an object type can be implicitly converted to a void∗ (§7.2 .1). A pointer (reference) to a derived class can be implicitly converted to a pointer (reference) to an accessible and unam- biguous base (§20.2). Note that a pointer to function or a pointer to member cannot be implicitly converted to a void∗. A constant expression (§10.4) that evaluates to 0 can be implicitly converted to a null pointer of any pointer type. Similarly, a constant expression that evaluates to 0 can be implicitly converted to a pointer-to-member type (§20.6). For example: int∗ p = (1+2)∗(2∗(1−1)); // OK, but weird Prefer nullptr (§7.2 .2). A T∗ can be implicitly converted to a const T∗ (§7.5). Similarly, a T& can be implicitly con- verted to a const T&. 10.5 .2 .4 Pointer-to-Member Conversions Pointers and references to members can be implicitly converted as described in §20.6 .3 . 10.5 .2 .5 Boolean Conversions Pointer, integral, and floating-point values can be implicitly converted to bool (§6.2 .2). A nonzero value converts to true; a zero value converts to false. For example: void f(int∗ p, int i) { bool is_not_zero = p; // true if p!=0 boolb2=i; // true if i!=0 // ... }
ptg10564057 270 Expressions Chapter 10 The pointer-to-bool conversion is useful in conditions, but confusing elsewhere: void fi(int); void fb(bool); void ff(int∗ p, int∗ q) { if (p) do_something(∗p); // OK if (q!=nullptr) do_something(∗q); // OK, but verbose // ... fi(p); // error: no pointer to int conversion fb(p); // OK: pointer to bool conversion (surprise!?) } Hope for a compiler warning for fb(p). 10.5 .2 .6 Floating-Integral Conversions When a floating-point value is converted to an integer value, the fractional part is discarded. In other words, conversion from a floating-point type to an integer type truncates. For example, the value of int(1.6) is 1. The behavior is undefined if the truncated value cannot be represented in the destination type. For example: inti=2.7; // i becomes 2 char b = 2000.7; // undefined for 8-bit chars: 2000 cannot be represented as an 8-bit char Conversions from integer to floating types are as mathematically correct as the hardware allows. Loss of precision occurs if an integral value cannot be represented exactly as a value of the floating type. For example: int i = float(1234567890); On a machine where both ints and floats are represented using 32 bits, the value of i is 1234567936. Clearly, it is best to avoid potentially value-destroying implicit conversions. In fact, compilers can detect and warn against some obviously dangerous conversions, such as floating to integral and long int to char. However, general compile-time detection is impractical, so the programmer must be careful. When ‘‘being careful’’ isn’t enough, the programmer can insert explicit checks. For example: char checked_cast(int i) { charc=i; // warning: not portable (§10.5 .2.1) if (i != c) throw std::runtime_error{"int−to−char check failed"}; return c; } void my_code(int i) { char c = checked_cast(i); // ... }
ptg10564057 Section 10.5 .2 .6 Floating-Integral Conversions 271 A more general technique for expressing checked conversions is presented in §25.2.5 .1 . To truncate in a way that is guaranteed to be portable requires the use of numeric_limits (§40.2). In initializations, truncation can be avoided by using the {}-initializer notation (§6.3 .5). 10.5.3 Usual Arithmetic Conversions These conversions are performed on the operands of a binary operator to bring them to a common type, which is then used as the type of the result: [1] If either operand is of type long double, the other is converted to long double. • Otherwise, if either operand is double, the other is converted to double. • Otherwise, if either operand is float, the other is converted to float. • Otherwise, integral promotions (§10.5 .1) are performed on both operands. [2] Otherwise, if either operand is unsigned long long, the other is converted to unsigned long long. • Otherwise, if one operand is a long long int and the other is an unsigned long int, then if a long long int can represent all the values of an unsigned long int, the unsigned long int is converted to a long long int; otherwise, both operands are converted to unsigned long long int. Otherwise, if either operand is unsigned long long, the other is converted to unsigned long long. • Otherwise, if one operand is a long int and the other is an unsigned int, then if a long int can represent all the values of an unsigned int, the unsigned int is converted to a long int; otherwise, both operands are converted to unsigned long int. • Otherwise, if either operand is long, the other is converted to long. • Otherwise, if either operand is unsigned, the other is converted to unsigned. • Otherwise, both operands are int. These rules make the result of converting an unsigned integer to a signed one of possibly larger size implementation-defined. That is yet another reason to avoid mixing unsigned and signed integers. 10.6 Advice [1] Prefer the standard library to other libraries and to ‘‘handcrafted code’’; §10.2 .8 . [2] Use character-level input only when you have to; §10.2 .3 . [3] When reading, always consider ill-formed input; §10.2.3 . [4] Prefer suitable abstractions (classes, algorithms, etc.) to direct use of language features (e.g ., ints, statements); §10.2 .8 . [5] Avoid complicated expressions; §10.3 .3 . [6] If in doubt about operator precedence, parenthesize; §10.3 .3 . [7] Avoid expressions with undefined order of evaluation; §10.3 .2 . [8] Avoid narrowing conversions; §10.5 .2 . [9] Define symbolic constants to avoid ‘‘magic constants’’; §10.4 .1 . [10] Avoid narrowing conversions; §10.5 .2 .
ptg10564057 This page intentionally left blank
ptg10564057 11 Select Operations When someone says “I want a programming language in which I need only say what I wish done,” give him a lollipop. – Alan Perlis • Etc. Operators Logical Operators; Bitwise Logical Operators; Conditional Expressions; Increment and Decrement • Free Store Memory Management; Arrays; Getting Memory Space; Overloading new • Lists Implementation Model; Qualified Lists; Unqualified Lists • Lambda Expressions Implementation Model; Alternatives to Lambdas; Capture; Call and Return; The Type of a Lambda • Explicit Type Conversion Construction; Named Casts; C-Style Cast; Function-Style Cast • Advice 11.1 Etc. Operators This section examines a mixed bag of simple operators: logical operators (&&, ||, and !), bitwise log- ical operators (&, |, ̃, <<, and >>), conditional expressions (?:), and increment and decrement opera- tors (++ and −−) . They have little in common beyond their details not fitting elsewhere in the dis- cussions of operators.
ptg10564057 274 Select Operations Chapter 11 11.1.1 Logical Operators The logical operators && (and), || (or), and ! (not) take operands of arithmetic and pointer types, convert them to bool, and return a bool result. The && and || operators evaluate their second argu- ment only if necessary, so they can be used to control evaluation order (§10.3 .2). For example: while (p && !whitespace(∗p)) ++p; Here, p is not dereferenced if it is the nullptr. 11.1.2 Bitwise Logical Operators The bitwise logical operators & (and), | (or), ˆ (exclusive or, xor), ̃ (complement), >> (right shift), and << (left shift) are applied to objects of integral types – that is, char, short, int, long, long long and their unsigned counterparts, and bool, wchar_t, char16_t, and char32_t. A plain enum (but not an enum class) can be implicitly converted to an integer type and used as an operand to bitwise logical operations. The usual arithmetic conversions (§10.5.3) determine the type of the result. A typical use of bitwise logical operators is to implement the notion of a small set (a bit vector). In this case, each bit of an unsigned integer represents one member of the set, and the number of bits limits the number of members. The binary operator & is interpreted as intersection, | as union, ˆ as symmetric difference, and ̃ as complement. An enumeration can be used to name the members of such a set. Here is a small example borrowed from an implementation of ostream: enum ios_base::iostate { goodbit=0, eofbit=1, failbit=2, badbit=4 }; The implementation of a stream can set and test its state like this: state = goodbit; // ... if (state&(badbit|failbit)) // stream not good The extra parentheses are necessary because & has higher precedence than | (§10.3). A function that reaches the end-of-input might report it like this: state |= eofbit; The |= operator is used to add to the state. A simple assignment, state=eofbit, would have cleared all other bits. These stream state flags are observable from outside the stream implementation. For example, we could see how the states of two streams differ like this: int old = cin.rdstate(); // rdstate() returns the state // ... use cin ... if (cin.rdstate()ˆold) { // has anything changed? // ... } Computing differences of stream states is not common. For other similar types, computing differ- ences is essential. For example, consider comparing a bit vector that represents the set of interrupts being handled with another that represents the set of interrupts waiting to be handled.
ptg10564057 Section 11.1 .2 Bitwise Logical Operators 275 Please note that this bit fiddling is taken from the implementation of iostreams rather than from the user interface. Convenient bit manipulation can be very important, but for reliability, maintain- ability, portability, etc., it should be kept at low levels of a system. For more general notions of a set, see the standard-library set (§31.4 .3) and bitset (§34.2 .2). Bitwise logical operations can be used to extract bit-fields from a word. For example, one could extract the middle 16 bits of a 32-bit int like this: constexpr unsigned short middle(int a) { static_assert(sizeof(int)==4,"unexpected int size"); static_assert(sizeof(short)==2,"unexpected short size"); return (a>>8)&0xFFFF; } int x = 0xFF00FF00; // assume sizeof(int)==4 short y = middle(x); // y = 0x00FF Using fields (§8.2 .7) is a convenient shorthand for such shifting and masking. Do not confuse the bitwise logical operators with the logical operators: &&, ||, and !. The latter return true or false, and they are primarily useful for writing the test in an if-, while-, or for-statement (§9.4, §9.5). For example, !0 (not zero) is the value true, which converts to 1, whereas ̃0 (comple- ment of zero) is the bit pattern all-ones, which in two’s complement representation is the value −1 . 11.1.3 Conditional Expressions Some if-statements can conveniently be replaced by conditional-expressions. For example: if(a<=b) max=b; else max=a; This is more directly expressed like this: max=(a<=b)?b:a; The parentheses around the condition are not necessary, but I find the code easier to read when they are used. Conditional expressions are important in that they can be used in constant expressions (§10.4). A pair of expressions e1 and e2 can be used as alternatives in a conditional expression, c?e1:e2, if they are of the same type or if there is a common type T, to which they can both be implicitly converted. For arithmetic types, the usual arithmetic conversions (§10.5 .3) are used to find that common type. For other types, either e1 must be implicitly convertible to e2’s type or vice versa. In addition, one branch may be a throw-expression (§13.5 .1). For example: void fct(int∗ p) { int i = (p) ? ∗p : std::runtime_error{"unexpected nullptr}; // ... }
ptg10564057 276 Select Operations Chapter 11 11.1.4 Increment and Decrement The ++ operator is used to express incrementing directly, rather than expressing it indirectly using a combination of an addition and an assignment. Provided lvalue has no side effects, ++lvalue means lvalue+=1, which again means lvalue=lvalue+1. The expression denoting the object to be incre- mented is evaluated once (only). Decrementing is similarly expressed by the −− operator. The operators ++ and −− can be used as both prefix and postfix operators. The value of ++x is the new (that is, incremented) value of x. For example, y=++x is equivalent to y=(x=x+1). The value of x++, however, is the old value of x. For example, y=x++ is equivalent to y=(t=x,x=x+1,t), where t is a variable of the same type as x. Like adding an int to a pointer, or subtracting it, ++ and −− on a pointer operate in terms of ele- ments of the array into which the pointer points; p++ makes p point to the next element (§7.4 .1). The ++ and −− operators are particularly useful for incrementing and decrementing variables in loops. For example, one can copy a zero-terminated C-style string like this: void cpy(char∗ p, const char∗ q) { while (∗p++ = ∗q++) ; } Like C, C++ is both loved and hated for enabling such terse, expression-oriented coding. Consider: while (∗p++ = ∗q++) ; This is more than a little obscure to non-C programmers, but because the style of coding is not uncommon, it is worth examining more closely. Consider first a more traditional way of copying an array of characters: int length = strlen(q); for (int i = 0; i<=length; i++) p[i] = q[i]; This is wasteful. The length of a zero-terminated string is found by reading the string looking for the terminating zero. Thus, we read the string twice: once to find its length and once to copy it. So we try this instead: int i; for (i = 0; q[i]!=0 ; i++) p[i] = q[i]; p[i] = 0; // terminating zero The variable i used for indexing can be eliminated because p and q are pointers: while (∗q!=0){ ∗p=∗q; p++; // point to next character q++; // point to next character } ∗p=0; //terminating zero Because the post-increment operation allows us first to use the value and then to increment it, we can rewrite the loop like this:
ptg10564057 Section 11.1 .4 Increment and Decrement 277 while (∗q!=0){ ∗p++ = ∗q++; } ∗p=0;//terminating zero The value of ∗p++ = ∗q++ is ∗q. We can therefore rewrite the example like this: while ((∗p++ = ∗q++) != 0) { } In this case, we don’t notice that ∗q is zero until we already have copied it into ∗p and incremented p. Consequently, we can eliminate the final assignment of the terminating zero. Finally, we can reduce the example further by observing that we don’t need the empty block and that the !=0 is redundant because the result of an integral condition is always compared to zero anyway. Thus, we get the version we set out to discover: while (∗p++ = ∗q++) ; Is this version less readable than the previous versions? Not to an experienced C or C++ program- mer. Is this version more efficient in time or space than the previous versions? Except for the first version that called strlen(), not really; the performance will be equivalent and often identical code will be generated. The most efficient way of copying a zero-terminated character string is typically the standard C- style string copy function: char∗ strcpy(char∗, const char∗); // from <string.h> For more general copying, the standard copy algorithm (§4.5, §32.5) can be used. Whenever possi- ble, use standard-library facilities in preference to fiddling with pointers and bytes. Standard- library functions may be inlined (§12.1 .3) or even implemented using specialized machine instruc- tions. Therefore, you should measure carefully before believing that some piece of handcrafted code outperforms library functions. Even if it does, the advantage may not exist on some other handware+compiler combination, and your alternative may give a maintainer a headache. 11.2 Free Store A named object has its lifetime determined by its scope (§6.3 .4). However, it is often useful to cre- ate an object that exists independently of the scope in which it was created. For example, it is com- mon to create objects that can be used after returning from the function in which they were created. The operator new creates such objects, and the operator delete can be used to destroy them. Objects allocated by new are said to be ‘‘on the free store’’ (also, ‘‘on the heap’’ or ‘‘in dynamic memory’’). Consider how we might write a compiler in the style used for the desk calculator (§10.2). The syntax analysis functions might build a tree of the expressions for use by the code generator: struct Enode { Token_value oper; Enode∗ left; Enode∗ right; // ... };
ptg10564057 278 Select Operations Chapter 11 Enode∗ expr(bool get) { Enode∗ left = term(get); for (;;) { switch (ts.current().kind) { case Kind::plus: case Kind::minus: left = new Enode {ts.current().kind,left,term(true)}; break; default: return left; // return node } } } In cases Kind::plus and Kind::minus,anewEnode is created on the free store and initialized by the value {ts.current().kind,left,term(true)}. The resulting pointer is assigned to left and eventually returned from expr(). I used the {}-list notation for specifying arguments. Alternatively, I could have used the old- style ()-list notation to specify an initializer. However, trying the = notation for initializing an object created using new results in an error: int∗p=newint=7;//error If a type has a default constructor, we can leave out the initializer, but built-in types are by default uninitialized. For example: auto pc = new complex<double>; // the complex is initialized to {0,0} auto pi = new int; // the int is uninitialized This can be confusing. To be sure to get default initialization, use {}. For example: auto pc = new complex<double>{}; // the complex is initialized to {0,0} auto pi = new int{}; // the int is initialized to 0 A code generator could use the Enodes created by expr() and delete them: void generate(Enode∗ n) { switch (n−>oper) { case Kind::plus: //usen delete n; // delete an Enode from the free store } } An object created by new exists until it is explicitly destroyed by delete. Then, the space it occu- pied can be reused by new. A C++ implementation does not guarantee the presence of a ‘‘garbage collector’’ that looks out for unreferenced objects and makes them available to new for reuse. Con- sequently, I will assume that objects created by new are manually freed using delete.
ptg10564057 Section 11.2 Free Store 279 The delete operator may be applied only to a pointer returned by new or to the nullptr. Applying delete to the nullptr has no effect. If the deleted object is of a class with a destructor (§3.2 .1 .2, §17.2), that destructor is called by delete before the object’s memory is released for reuse. 11.2.1 Memory Management The main problems with free store are: • Leaked objects: People use new and then forget to delete the allocated object. • Premature deletion: People delete an object that they have some other pointer to and later use that other pointer. • Double deletion: An object is deleted twice, invoking its destructor (if any) twice. Leaked objects are potentially a bad problem because they can cause a program to run out of space. Premature deletion is almost always a nasty problem because the pointer to the ‘‘deleted object’’ no longer points to a valid object (so reading it may give bad results) and may indeed point to memory that has been reused for another object (so writing to it may corrupt an unrelated object). Consider this example of very bad code: int∗ p1 = new int{99}; int∗ p2 = p1; // potential trouble delete p1; // now p2 doesn’t point to a valid object p1 = nullptr; // gives a false sense of safety char∗ p3 = new char{'x'}; // p3 may now point to the memory pointed to by p2 ∗p2 = 999; // this may cause trouble cout << ∗p3 << '\n'; // may not print x Double deletion is a problem because resource managers typically cannot track what code owns a resource. Consider: void sloppy() // very bad code { int∗ p = new int[1000]; // acquire memory // ... use *p ... delete[] p; // release memory // ... wait a while ... delete[] p; // but sloppy() does not own *p } By the second delete[], the memory pointed to by ∗p may have been reallocated for some other use and the allocator may get corrupted. Replace int with string in that example, and we’ll see string’s destructor trying to read memory that has been reallocated and maybe overwritten by other code, and using what it read to try to delete memory. In general, a double deletion is undefined behavior and the results are unpredictable and usually disastrous. The reason people make these mistakes is typically not maliciousness and often not even simple sloppiness; it is genuinely hard to consistently deallocate every allocated object in a large program (once and at exactly the right point in a computation). For starters, analysis of a localized part of a program will not detect these problems because an error usually involves several separate parts.
ptg10564057 280 Select Operations Chapter 11 As alternatives to using ‘‘naked’’ news and deletes, I can recommend two general approaches to resource management that avoid such problems: [1] Don’t put objects on the free store if you don’t have to; prefer scoped variables. [2] When you construct an object on the free store, place its pointer into a manager object (sometimes called a handle) with a destructor that will destroy it. Examples are string, vector and all the other standard-library containers, unique_ptr (§5.2 .1, §34.3 .1), and shared_ptr (§5.2 .1, §34.3 .2). Wherever possible, have that manager object be a scoped variable. Many classical uses of free store can be eliminated by using move semantics (§3.3, §17.5.2) to return large objects represented as manager objects from functions. This rule [2] is often referred to as RAII (‘‘Resource Acquisition Is Initialization’’; §5.2, §13.3) and is the basic technique for avoiding resource leaks and making error handling using exceptions sim- ple and safe. The standard-library vector is an example of these techniques: void f(const string& s) { vector<char> v; for(autoc:s) v.push_back(c); // ... } The vector keeps its elements on the free store, but it handles all allocations and deallocations itself. In this example, push_back() does news to acquire space for its elements and deletes to free space that it no longer needs. However, the users of vector need not know about those implementation details and will just rely on vector not leaking. The Token_stream from the calculator example is an even simpler example (§10.2.2). There, a user can use new and hand the resulting pointer to a Token_stream to manage: Token_stream ts{new istringstream{some_string}}; We do not need to use the free store just to get a large object out of a function. For example: string reverse(const string& s) { string ss; for (int i=s.size()−1; 0<=i; −−i) ss.push_back(s[i]); return ss; } Like vector,astring is really a handle to its elements. So, we simply move the ss out of reverse() rather than copying any elements (§3.3 .2). The resource management ‘‘smart pointers’’ (e.g ., unique_ptr and smart_ptr) are a further exam- ple of these ideas (§5.2 .1, §34.3 .1). For example: void f(int n) { int∗ p1 = new int[n]; // potential trouble unique_ptr<int[]> p2 {new int[n]};
ptg10564057 Section 11.2 .1 Memory Management 281 // ... if (n%2) throw runtime_error("odd"); delete[] p1; // we may never get here } For f(3) the memory pointed to by p1 is leaked, but the memory pointed to by p2 is correctly and implicitly deallocated. My rule of thumb for the use of new and delete is ‘‘no naked news’’; that is, new belongs in con- structors and similar operations, delete belongs in destructors, and together they provide a coherent memory management strategy. In addition, new is often used in arguments to resource handles. If everything else fails (e.g ., if someone has a lot of old code with lots of undisciplined use of new), C++ offers a standard interface to a garbage collector (§34.5). 11.2.2 Arrays Arrays of objects can also be created using new. For example: char∗ save_string(const char∗ p) { char∗ s = new char[strlen(p)+1]; strcpy(s,p); //copyfromptos return s; } int main(int argc, char∗ argv[]) { if (argc < 2) exit(1); char∗ p = save_string(argv[1]); // ... delete[] p; } The ‘‘plain’’ operator delete is used to delete individual objects; delete[] is used to delete arrays. Unless you really must use a char∗ directly, the standard-library string can be used to simplify the save_string(): string save_string(const char∗ p) { return string{p}; } int main(int argc, char∗ argv[]) { if (argc < 2) exit(1); string s = save_string(argv[1]); // ... } In particular, the new[] and the delete[] vanished.
ptg10564057 282 Select Operations Chapter 11 To deallocate space allocated by new, delete and delete[] must be able to determine the size of the object allocated. This implies that an object allocated using the standard implementation of new will occupy slightly more space than a static object. At a minimum, space is needed to hold the object’s size. Usually two or more words per allocation are used for free-store management. Most modern machines use 8-byte words. This overhead is not significant when we allocate many objects or large objects, but it can matter if we allocate lots of small objects (e.g ., intsorPoints) on the free store. Note that a vector (§4.4 .1, §31.4) is a proper object and can therefore be allocated and deallo- cated using plain new and delete. For example: void f(int n) { vector<int>∗ p = new vector<int>(n); // individual object int∗ q = new int[n]; // array // ... delete p; delete[] q; } The delete[] operator may be applied only to a pointer to an array returned by new of an array or to the null pointer (§7.2 .2). Applying delete[] to the null pointer has no effect. However, do not use new to create local objects. For example: void f1() { X∗ p=newX; // ... use *p ... delete p; } That’s verbose, inefficient, and error-prone (§13.3). In particular, a return or an exception thrown before the delete will cause a memory leak (unless even more code is added). Instead, use a local variable: void f2() { Xx; //...usex... } The local variable x is implicitly destroyed upon exit from f2. 11.2.3 Getting Memory Space The free-store operators new, delete, new[], and delete[] are implemented using functions presented in the <new> header: void∗ operator new(size_t); // allocate space for individual object void operator delete(void∗ p); // if (p) deallocate space allocated using operator new()
ptg10564057 Section 11.2 .3 Getting Memory Space 283 void∗ operator new[](size_t); // allocate space for array void operator delete[](void∗ p); // if (p) deallocate space allocated using operator new[]() When operator new needs to allocate space for an object, it calls operator new() to allocate a suitable number of bytes. Similarly, when operator new needs to allocate space for an array, it calls operator new[](). The standard implementations of operator new() and operator new[]() do not initialize the mem- ory returned. The allocation and deallocation functions deal in untyped and uninitialized memory (often called ‘‘raw memory’’), as opposed to typed objects. Consequently, they take arguments or return values of type void∗. The operators new and delete handle the mapping between this untyped-mem- ory layer and the typed-object layer. What happens when new can find no store to allocate? By default, the allocator throws a stan- dard-library bad_alloc exception (for an alternative, see §11.2 .4.1). For example: void f() { vector<char∗>v; try { for (;;) { char ∗ p = new char[10000]; // acquire some memory v.push_back(p); // make sure the new memory is referenced p[0] = 'x'; // use the new memory } } catch(bad_alloc) { cerr << "Memory exhausted!\n"; } } However much memory we have available, this will eventually invoke the bad_alloc handler. Please be careful: the new operator is not guaranteed to throw when you run out of physical main memory. So, on a system with virtual memory, this program can consume a lot of disk space and take a long time doing so before the exception is thrown. We can specify what new should do upon memory exhaustion; see §30.4 .1 .3. In addition to the functions defined in <new>, a user can define operator new(), etc., for a specific class (§19.2 .5). Class members operator new(), etc., are found and used in preference to the ones from <new> according to the usual scope rules. 11.2.4 Overloading new By default, operator new creates its object on the free store. What if we wanted the object allocated elsewhere? Consider a simple class: class X { public: X(int); // ... };
ptg10564057 284 Select Operations Chapter 11 We can place objects anywhere by providing an allocator function (§11.2.3) with extra arguments and then supplying such extra arguments when using new: void∗ operator new(size_t, void∗ p) { return p; } // explicit placement operator void∗ buf = reinterpret_cast<void∗>(0xF00F); // significant address X∗ p2 = new(buf) X; // construct an X at buf; // invokes: operator new(sizeof(X),buf) Because of this usage, the new(buf) X syntax for supplying extra arguments to operator new() is known as the placement syntax. Note that every operator new() takes a size as its first argument and that the size of the object allocated is implicitly supplied (§19.2 .5). The operator new() used by the new operator is chosen by the usual argument matching rules (§12.3); every operator new() has a size_t as its first argument. The ‘‘placement’’ operator new() is the simplest such allocator. It is defined in the standard header <new>: void∗ operator new (size_t sz, void∗ p) noexcept; // place object of size sz at p void∗ operator new[](size_t sz, void∗ p) noexcept; // place object of size sz at p void operator delete (void∗ p, void∗) noexcept; // if (p) make *p invalid void operator delete[](void∗ p, void∗) noexcept; // if (p) make *p invalid The ‘‘placement delete’’ operators do nothing except possibly inform a garbage collector that the deleted pointer is no longer safely derived (§34.5). The placement new construct can also be used to allocate memory from a specific arena: class Arena { public: virtual void∗ alloc(size_t) =0; virtual void free(void∗)=0; // ... }; void∗ operator new(size_t sz, Arena∗ a) { return a−>alloc(sz); } Now objects of arbitrary types can be allocated from different Arenas as needed. For example: extern Arena∗ Persistent; extern Arena∗ Shared; void g(int i) { X∗ p = new(Persistent) X(i); // X in persistent storage X∗ q = new(Shared) X(i); // X in shared memory // ... }
ptg10564057 Section 11.2 .4 Overloading new 285 Placing an object in an area that is not (directly) controlled by the standard free-store manager implies that some care is required when destroying the object. The basic mechanism for that is an explicit call of a destructor: void destroy(X∗ p, Arena∗ a) { p−>̃X(); // call destructor a−>free(p); // free memory } Note that explicit calls of destructors should be avoided except in the implementation of resource management classes. Even most resource handles can be written using new and delete. However, it would be hard to implement an efficient general container along the lines of the standard-library vector (§4.4.1, §31.3 .3) without using explicit destructor calls. A novice should think thrice before calling a destructor explicitly and also should ask a more experienced colleague before doing so. See §13.6 .1 for an example of how placement new can interact with exception handling. There is no special syntax for placement of arrays. Nor need there be, since arbitrary types can be allocated by placement new. However, an operator delete() can be defined for arrays (§11.2 .3). 11.2 .4 .1 nothrow new In programs where exceptions must be avoided (§13.1 .5), we can use nothrow versions of new and delete. For example: void f(int n) { int∗ p = new(nothrow) int[n]; // allocate n ints on the free store if (p==nullptr) { // no memory available // ... handle allocation error ... } // ... operator delete(nothrow,p); // deallocate *p } That nothrow is the name of an object of the standard-library type nothrow_t that is used for disam- biguation; nothrow and nothrow_t are declared in <new>. The functions implementing this are found in <new>: void∗ operator new(size_t sz, const nothrow_t&) noexcept; // allocate sz bytes; // return nullptr if allocation failed void operator delete(void∗ p, const nothrow_t&) noexcept; // deallocate space allocated by new void∗ operator new[](size_t sz, const nothrow_t&) noexcept; // allocate sz bytes; // return nullptr if allocation failed void operator delete[](void∗ p, const nothrow_t&) noexcept; // deallocate space allocated by new These operator new functions return nullptr, rather than throwing bad_alloc, if there is not sufficient memory to allocate.
ptg10564057 286 Select Operations Chapter 11 11.3 Lists In addition to their use for initializing named variables (§6.3 .5.2), {}-lists can be used as expressions in many (but not all) places. They can appear in two forms: [1] Qualified by a type, T{...}, meaning ‘‘create an object of type T initialized by T{...}’’ ; §11.3 .2 [2] Unqualified {...}, for which the the type must be determined from the context of use; §11.3 .3 For example: structS{inta,b;}; struct SS { double a, b; }; void f(S); // f() takes an S void g(S); void g(SS); // g() is overloaded void h() { f({1,2}); // OK: call f(S{1,2}) g({1,2}); // error: ambiguous g(S{1,2}); // OK: call g(S) g(SS{1,2}); // OK: call g(SS) } As in their use for initializing named variables (§6.3 .5), lists can have zero, one, or more elements. A {}-list is used to construct an object of some type, so the number of elements and their types must be what is required to construct an object of that type. 11.3.1 Implementation Model The implementation model for {}-lists comes in three parts: • If the {}-list is used as constructor arguments, the implementation is just as if you had used a ()-list. List elements are not copied except as by-value constructor arguments. • If the {}-list is used to initialize the elements of an aggregate (an array or a class without a constructor), each list element initializes an element of the aggregate. List elements are not copied except as by-value arguments to aggregate element constructors. • If the {}-list is used to construct an initializer_list object each list element is used to initialize an element of the underlying array of the initializer_list. Elements are typically copied from the initializer_list to wherever we use them. Note that this is the general model that we can use to understand the semantics of a {}-list; a com- piler may apply clever optimizations as long as the meaning is preserved. Consider: vector<double> v = {1, 2, 3.14}; The standard-library vector has an initializer-list constructor (§17.3 .4), so the initializer list
ptg10564057 Section 11.3 .1 Implementation Model 287 {1,2,3.14} is interpreted as a temporary constructed and used like this: const double temp[] = {double{1}, double{2}, 3.14 } ; const initializer_list<double> tmp(temp,sizeof(temp)/sizeof(double)); vector<double> v(tmp); That is, the compiler constructs an array containing the initializers converted to the desired type (here, double). This array is passed to vectors initializer-list constructor as an initializer_list. The initializer-list constructor then copies the values from the array into its own data structure for ele- ments. Note that an initializer_list is a small object (probably two words), so passing it by value makes sense. The underlying array is immutable, so there is no way (within the standard’s rules) that the meaning of a {}-list can change between two uses. Consider: void f() { initializer_list<int> lst {1,2,3}; cout << ∗lst.begin() << '\n'; ∗lst.begin() = 2; // error: lst is immutable cout << ∗lst.begin() << '\n'; } In particular, having a {}-list be immutable implies that a container taking elements from it must use a copy operation, rather than a move operation. The lifetime of a {}-list (and its underlying array) is determined by the scope in which it is used (§6.4 .2). When used to initialize a variable of type initializer_list<T>, the list lives as long as the variable. When used in an expression (including as an initializer to a variable of some other type, such as vector<T>), the list is destroyed at the end of its full expression. 11.3.2 Qualified Lists The basic idea of initializer lists as expressions is that if you can initialize a variable x using the notation Tx{v}; then you can create an object with the same value as an expression using T{v} or new T{v}. Using new places the object on the free store and returns a pointer to it, whereas ‘‘plain T{v}’’ makes a temporary object in the local scope (§6.4.2). For example: structS{inta,b;}; void f() { S v {7,8}; // direct initialization of a variable v = S{7,8}; // assign using qualified list S∗ p = new S{7,8}; // construct on free store using qualified list } The rules constructing an object using a qualified list are those of direct initialization (§16.2 .6).
ptg10564057 288 Select Operations Chapter 11 One way of looking at a qualified initializer list with one element is as a conversion from one type to another. For example: template<class T> T square(T x) { return x∗x; } void f(int i) { double d = square(double{i}); complex<double> z = square(complex<double>{i}); } That idea is explored further in §11.5 .1 . 11.3.3 Unqualified Lists A unqualified list is used where an expected type is unambiguously known. It can be used as an expression only as: • A function argument • A return value • The right-hand operand of an assignment operator (=, +=, ∗=, etc.) • A subscript For example: int f(double d, Matrix& m) { int v {7}; // initializer (direct initialization) int v2 = {7}; // initializer (copy initialization) int v3 = m[{2,3}]; // assume m takes value pairs as subscripts v={8}; // right-hand operand of assignment v += {88}; // right-hand operand of assignment {v}=9; // error: not left-hand operand of assignment v = 7+{10}; // error: not an operand of a non-assignment operator f({10.0}); // function argument return {11}; // return value } The reason that an unqualified list is not allowed on the left-hand side of assignments is primarily that the C++ grammar allows { in that position for compound statements (blocks), so that readabil- ity would be a problem for humans and ambiguity resolution would be tricky for compilers. This is not an insurmountable problem, but it was decided not to extend C++ in that direction. When used as the initializer for a named object without the use of a = (as for v above), an unqualified {}-list performs direct initialization (§16.2 .6). In all other cases, it performs copy initialization (§16.2 .6). In particular, the otherwise redundant = in an initializer restricts the set of initializations that can be performed with a given {}-list.
ptg10564057 Section 11.3 .3 Unqualified Lists 289 The standard-library type initializer_list<T> is used to handle variable-length {}-lists (§12.2 .3). Its most obvious use is to allow initializer lists for user-defined containers (§3.2 .1 .3), but it can also be used directly; for example: int high_value(initializer_list<int> val) { int high = numeric_traits<int>lowest(); if (val.size()==0) return high; for (auto x : val) if (x>high) high = x; return high; } int v1 = high_value({1,2,3,4,5,6,7}); int v2 = high_value({−1,2,v1,4,−9,20,v1}); A {}-list is the simplest way of dealing with homogeneous lists of varying lengths. However, beware that zero elements can be a special case. If so, that case should be handled by a default con- structor (§17.3 .3). The type of a {}-list can be deduced (only) if all elements are of the same type. For example: auto x0 = {}; // error (no element type) auto x1 = {1}; // initializer_list<int> auto x2 = {1,2}; // initializer_list<int> auto x3 = {1,2,3}; // initializer_list<int> auto x4 = {1,2.0}; // error: nonhomogeneous list Unfortunately, we do not deduce the type of an unqualified list for a plain template argument. For example: template<typename T> void f(T); f({}); // error: type of initializer is unknown f({1}); // error: an unqualified list does not match ‘‘plain T’’ f({1,2}); // error: an unqualified list does not match ‘‘plain T’’ f({1,2,3}); // error: an unqualified list does not match ‘‘plain T’’ I say ‘‘unfortunately’’ because this is a language restriction, rather than a fundamental rule. It would be technically possible to deduce the type of those {}-lists as initializer_list<int>, just like we do for auto initializers. Similarly, we do not deduce the element type of a container represented as a template. For example: template<class T> void f2(const vector<T>&); f2({1,2,3}); // error: cannot deduce T f2({"Kona","Sidney"}); // error: cannot deduce T
ptg10564057 290 Select Operations Chapter 11 This too is unfortunate, but it is a bit more understandable from a language-technical point of view: nowhere in those calls does it say vector. To deduce T the compiler would first have to decide that the user really wanted a vector and then look into the definition of vector to see if it has a construc- tor that accepts {1,2,3}. In general, that would require an instantiation of vector (§26.2). It would be possible to handle that, but it could be costly in compile time, and the opportunities for ambiguities and confusion if there were many overloaded versions of f2() are reasons for caution. To call f2(),be more specific: f2(vector<int>{1,2,3}); // OK f2(vector<string>{"Kona","Sidney"}); // OK 11.4 Lambda Expressions A lambda expression, sometimes also referred to as a lambda function or (strictly speaking incor- rectly, but colloquially) as a lambda, is a simplified notation for defining and using an anonymous function object. Instead of defining a named class with an operator(), later making an object of that class, and finally invoking it, we can use a shorthand. This is particularly useful when we want to pass an operation as an argument to an algorithm. In the context of graphical user interfaces (and elsewhere), such operations are often referred to as callbacks. This section focuses on technical aspects of lambdas; examples and techniques for the use of lambdas can be found elsewhere (§3.4 .3, §32.4, §33.5 .2). A lambda expression consists of a sequence of parts: • A possibly empty capture list, specifying what names from the definition environment can be used in the lambda expression’s body, and whether those are copied or accessed by refer- ence. The capture list is delimited by [] (§11.4.3). • An optional parameter list, specifying what arguments the lambda expression requires. The parameter list is delimited by () (§11.4 .4). • An optional mutable specifier, indicating that the lambda expression’s body may modify the state of the lambda (i.e., change the lambda’s copies of variables captured by value) (§11.4.3 .4). • An optional noexcept specifier. • An optional return type declaration of the form −> type (§11.4.4). •A body, specifying the code to be executed. The body is delimited by {} (§11.4 .3). The details of passing arguments, returning results, and specifying the body are those of functions and are presented in Chapter 12. The notion of ‘‘capture’’ of local variables is not provided for functions. This implies that a lambda can act as a local function even though a function cannot. 11.4.1 Implementation Model Lambda expressions can be implemented in a variety of ways, and there are some rather effective ways of optimizing them. However, I find it useful to understand the semantics of a lambda by considering it a shorthand for defining and using a function object. Consider a relatively simple example:
ptg10564057 Section 11.4 .1 Implementation Model 291 void print_modulo(const vector<int>& v, ostream& os, int m) // output v[i] to os if v[i]%m==0 { for_each(begin(v),end(v), [&os,m](int x) { if (x%m==0) os << x << '\n'; } ); } To see what this means, we can define the equivalent function object: class Modulo_print { ostream& os; // members to hold the capture list int m; public: Modulo_print(ostream& s, int mm) :os(s), m(mm) {} // capture void operator()(int x) const {if(x%m==0)os<<x<<'\n';} }; The capture list, [&os,m], becomes two member variables and a constructor to initialize them. The & before os means that we should store a reference, and the absence of a & for m means that we should store a copy. This use of & mirrors its use in function argument declarations. The body of the lambda simply becomes the body of the operator()(). Since the lambda doesn’t return a value, the operator()() is void. By default, operator()() is const, so that the lambda body doesn’t modify the captured variables. That’s by far the most common case. Should you want to modify the state of a lambda from its body, the lambda can be declared mutable (§11.4 .3.4). This corresponds to an operator()() not being declared const. An object of a class generated from a lambda is called a closure object (or simply a closure). We can now write the original function like this: void print_modulo(const vector<int>& v, ostream& os, int m) // output v[i] to os if v[i]%m==0 { for_each(begin(v),end(v),Modulo_print{os,m}); } If a lambda potentially captures every local variable by reference (using the capture list [&]), the closure may be optimized to simply contain a pointer to the enclosing stack frame. 11.4.2 Alternatives to Lambdas That final version of print_modulo() is actually quite attractive, and naming nontrivial operations is generally a good idea. A separately defined class also leaves more room for comments than does a lambda embedded in some argument list. However, many lambdas are small and used only once. For such uses, the realistic equivalent involves a local class defined immediately before its (only) use. For example:
ptg10564057 292 Select Operations Chapter 11 void print_modulo(const vector<int>& v, ostream& os, int m) // output v[i] to os if v[i]%m==0 { class Modulo_print { ostream& os; // members to hold the capture list int m; public: Modulo_print (ostream& s, int mm) :os(s), m(mm) {} // capture void operator()(int x) const {if(x%m==0)os<<x<<'\n';} }; for_each(begin(v),end(v),Modulo_print{os,m}); } Compared to that, the version using the lambda is a clear winner. If we really want a name, we can just name the lambda: void print_modulo(const vector<int>& v, ostream& os, int m) // output v[i] to os if v[i]%m==0 { auto Modulo_print = [&os,m] (int x) { if (x%m==0) os << x << '\n'; }; for_each(begin(v),end(v),Modulo_print); } Naming the lambda is often a good idea. Doing so forces us to consider the design of the operation a bit more carefully. It also simplifies code layout and allows for recursion (§11.4 .5). Writing a for-loop is an alternative to using a lambda with a for_each(). Consider: void print_modulo(const vector<int>& v, ostream& os, int m) // output v[i] to os if v[i]%m==0 { for(autox:v) if (x%m==0) os << x << '\n'; } Many would find this version much clearer than any of the lambda versions. However, for_each is a rather special algorithm, and vector<int> is a very specific container. Consider generalizing print_modulo() to handle arbitrary containers: template<class C> void print_modulo(const C& v, ostream& os, int m) // output v[i] to os if v[i]%m==0 { for(autox:v) if (x%m==0) os << x << '\n'; } This version works nicely for a map. The C++ range-for-statement specifically caters to the special case of traversing a sequence from its beginning to its end. The STL containers make such
ptg10564057 Section 11.4 .2 Alternatives to Lambdas 293 traversals easy and general. For example, using a for-statement to traverse a map gives a depth-first traversal. How would we do a breadth-first traversal? The for-loop version of print_modulo() is not amenable to change, so we have to rewrite it to an algorithm. For example: template<class C> void print_modulo(const C& v, ostream& os, int m) // output v[i] to os if v[i]%m==0 { breadth_first(begin(v),end(v), [&os,m](int x) { if (x%m==0) os << x << '\n'; } ); } Thus, a lambda can be used as ‘‘the body’’ for a generalized loop/traversal construct represented as an algorithm. Using for_each rather than breadth_first would give depth-first traversal. The performance of a lambda as an argument to a traversal algorithm is equivalent (typically identical) to that of the equivalent loop. I have found that to be quite consistent across implementa- tions and platforms. The implication is that we have to base our choice between ‘‘algorithm plus lambda’’ and ‘‘for-statement with body’’ on stylistic grounds and on estimates of extensibility and maintainability. 11.4.3 Capture The main use of lambdas is for specifying code to be passed as arguments. Lambdas allow that to be done ‘‘inline’’ without having to name a function (or function object) and use it elsewhere. Some lambdas require no access to their local environment. Such lambdas are defined with the empty lambda introducer []. For example: void algo(vector<int>& v) { sort(v.begin(),v.end()); // sort values // ... sort(v.begin(),v.end(),[](int x, int y) { return abs(x)<abs(y); }); // sort absolute values // ... } If we want to access local names, we have to say so or get an error: void f(vector<int>& v) { bool sensitive = true; // ... sort(v.begin(),v.end(), [](int x, int y) { return sensitive ? x<y : abs(x)<abs(y); } // error: can’t access sensitive ); } I used the lambda introducer []. This is the simplest lambda introducer and does not allow the lambda to refer to names in the calling environment. The first character of a lambda expression is always [. A lambda introducer can take various forms:
ptg10564057 294 Select Operations Chapter 11 • []: an empty capture list. This implies that no local names from the surrounding context can be used in the lambda body. For such lambda expressions, data is obtained from arguments or from nonlocal variables. • [&]: implicitly capture by reference. All local names can be used. All local variables are accessed by reference. • [=]: implicitly capture by value. All local names can be used. All names refer to copies of the local variables taken at the point of call of the lambda expression. • [capture-list]: explicit capture; the capture-list is the list of names of local variables to be captured (i.e ., stored in the object) by reference or by value. Variables with names preceded by & are captured by reference. Other variables are captured by value. A capture list can also contain this and names followed by ... as elements. • [&, capture-list]: implicitly capture by reference all local variables with names not men- tioned in the list. The capture list can contain this. Listed names cannot be preceded by &. Variables named in the capture list are captured by value. • [=, capture-list]: implicitly capture by value all local variables with names not mentioned in the list. The capture list cannot contain this. The listed names must be preceded by &. Vari- ables named in the capture list are captured by reference. Note that a local name preceded by & is always captured by reference and a local name not pre- ceded by & is always captured by value. Only capture by reference allows modification of variables in the calling environment. The capture-list cases are used for fine-grained control over what names from the call environ- ment are used and how. For example: void f(vector<int>& v) { bool sensitive = true; // ... sort(v.begin(),v.end() [sensitive](int x, int y) { return sensitive ? x<y : abs(x)<abs(y); } ); } By mentioning sensitive in the capture list, we make it accessible from within the lambda. By not specifying otherwise, we ensure that the capture of sensitive is done ‘‘by value’’; just as for argu- ment passing, passing a copy is the default. Had we wanted to capture sensitive ‘‘by reference,’’ we could have said so by adding a & before sensitive in the capture list: [&sensitive]. The choice between capturing by value and by reference is basically the same as the choice for function arguments (§12.2). We use a reference if we need to write to the captured object or if it is large. However, for lambdas, there is the added concern that a lambda might outlive its caller (§11.4.3 .1). When passing a lambda to another thread, capturing by value ([=]) is typically best: accessing another thread’s stack through a reference or a pointer can be most disruptive (to perfor- mance or correctness), and trying to access the stack of a terminated thread can lead to extremely difficult-to-find errors. If you need to capture a variadic template (§28.6) argument, use .... For example:
ptg10564057 Section 11.4 .3 Capture 295 template<typename... Var> void algo(int s, Var... v) { auto helper = [&s,&v...] { return s∗(h1(v...)+h2(v...)); } // ... } Beware that is it easy to get too clever about capture. Often, there is a choice between capture and argument passing. When that’s the case, capture is usually the least typing but has the greatest potential for confusion. 11.4 .3 .1 Lambda and Lifetime A lambda might outlive its caller. This can happen if we pass a lambda to a different thread or if the callee stores away the lambda for later use. For example: void setup(Menu& m) { // ... Point p1, p2, p3; // compute positions of p1, p2, and p3 m.add("draw triangle",[&]{ m.draw(p1,p2,p3); }); // probable disaster // ... } Assuming that add() is an operation that adds a (name,action) pair to a menu and that the draw() operation makes sense, we are left with a time bomb: the setup() completes and later – maybe min- utes later – a user presses the draw triangle button and the lambda tries to access the long-gone local variables. A lambda that wrote to a variable caught by reference would be even worse in that situa- tion. If a lambda might outlive its caller, we must make sure that all local information (if any) is copied into the closure object and that values are returned through the return mechanism (§12.1 .4) or through suitable arguments. For the setup() example, that is easily done: m.add("draw triangle",[=]{ m.draw(p1,p2,p3); }); Think of the capture list as the initializer list for the closure object and [=] and [&] as short-hand notation (§11.4.1). 11.4 .3 .2 Namespace Names We don’t need to ‘‘capture’’ namespace variables (including global variables) because they are always accessible (provided they are in scope). For example: template<typename U, typename V> ostream& operator<<(ostream& os, const pair<U,V>& p) { return os << '{' << p.first << ',' << p.second << '}'; }
ptg10564057 296 Select Operations Chapter 11 void print_all(const map<string,int>& m, const string& label) { cout << label << ":\n{\n"; for_each(m.begin(),m.end(), [](const pair<string,int>& p) { cout << p << '\n'; } ); cout << "}\n"; } Here, we don’t need to capture cout or the output operator for pair. 11.4 .3 .3 Lambda and this How do we access members of a class object from a lambda used in a member function? We can include class members in the set of names potentially captured by adding this to the capture list. This is used when we want to use a lambda in the implementation of a member function. For example, we might have a class for building up requests and retrieving results: class Request { function<map<string,string>(const map<string,string>&)> oper; // operation map<string,string> values; // arguments map<string,string> results; // targets public: Request(const string& s); // parse and store request void execute() { [this]() { results=oper(values); } // do oper to values yielding results } }; Members are always captured by reference. That is, [this] implies that members are accessed through this rather than copied into the lambda. Unfortunately, [this] and [=] are incompatible. This implies that incautious use can lead to race conditions in multi-threaded programs (§42.4 .6). 11.4 .3 .4 mutable Lambdas Usually, we don’t want to modify the state of the function object (the closure), so by default we can’t. That is, the operator()() for the generated function object (§11.4 .1) is a const member func- tion. In the unlikely event that we want to modify the state (as opposed to modifying the state of some variable captured by reference; §11.4.3), we can declare the lambda mutable. For example: void algo(vector<int>& v) { int count = v.size(); std::generate(v.begin(),v.end(), [count]()mutable{ return −−count; } ); } The −−count decrements the copy of v’s size stored in the closure.
ptg10564057 Section 11.4 .4 Call and Return 297 11.4.4 Call and Return The rules for passing arguments to a lambda are the same as for a function (§12.2), and so are the rules for returning results (§12.1 .4). In fact, with the exception of the rules for capture (§11.4 .3) most rules for lambdas are borrowed from the rules for functions and classes. However, two irregu- larities should be noted: [1] If a lambda expression does not take any arguments, the argument list can be omitted. Thus, the minimal lambda expression is []{}. [2] A lambda expression’s return type can be deduced from its body. Unfortunately, that is not also done for a function. If a lambda body does not have a return-statement, the lambda’s return type is void. If a lambda body consists of just a single return-statement, the lambda’s return type is the type of the return’s expression. If neither is the case, we have to explicitly supply a return type. For example: void g(double y) { [&]{ f(y); } // return type is void auto z1 = [=](int x){ return x+y; } // return type is double auto z2 = [=,y]{ if (y) return 1; else return 2; } // error: body too complicated // for return type deduction autoz3=[y](){return1:2;} // return type is int auto z4 = [=,y]()−>int { if (y) return 1; else return 2; } // OK: explicit return type } When the suffix return type notation is used, we cannot omit the argument list. 11.4.5 The Type of a Lambda To allow for optimized versions of lambda expressions, the type of a lambda expression is not defined. However, it is defined to be the type of a function object in the style presented in §11.4 .1. This type, called the closure type, is unique to the lambda, so no two lambdas have the same type. Had two lambdas had the same type, the template instantiation mechanism might have gotten con- fused. A lambda is of a local class type with a constructor and a const member function opera- tor()(). In addition to using a lambda as an argument, we can use it to initialize a variable declared auto or std::function<R(AL)> where R is the lambda’s return type and AL is its argument list of types (§33.5.3). For example, I might try to write a lambda to reverse the characters in a C-style string: auto rev = [&rev](char∗ b, char∗ e) {if(1<e−b) { swap(∗b,∗−−e); rev(++b,e); } }; // error However, that’s not possible because I cannot use an auto variable before its type has been deduced. Instead, I can introduce a name and then use it: void f(string& s1, string& s2) { function<void(char∗ b, char∗ e)> rev = [&](char∗ b, char∗ e) { if (1<e−b) { swap(∗b,∗−−e); rev(++b,e); } };
ptg10564057 298 Select Operations Chapter 11 rev(&s1[0],&s1[0]+s1.size()); rev(&s2[0],&s2[0]+s2.size()); } Now, the type of rev is specified before it is used. If we just want to name a lambda, rather than using it recursively, auto can simplify things: void g(vector<string>& vs1, vector<string>& vs2) { auto rev = [&](char∗ b, char∗ e) { while (1<e−b) swap(∗b++,∗−−e); }; rev(&s1[0],&s1[0]+s1.size()); rev(&s2[0],&s2[0]+s2.size()); } A lambda that captures nothing can be assigned to a pointer to function of an appropriate type. For example: double (∗p1)(double) = [](double a) { return sqrt(a); }; double (∗p2)(double) = [&](double a) { return sqrt(a); }; // error: the lambda captures double (∗p3)(int) = [](int a) { return sqrt(a); }; // error: argument types do not match 11.5 Explicit Type Conversion Sometimes, we have to convert a value of one type into a value of another. Many (arguably too many) such conversions are done implicitly according to the language rules (§2.2 .2, §10.5). For example: double d = 1234567890; // integer to floating-point inti=d; // floating-point to integer In other cases, we have to be explicit. For logical and historical reasons, C++ offers explicit type conversion operations of varying convenience and safety: • Construction, using the {} notation, providing type-safe construction of new values (§11.5.1) • Named conversions, providing conversions of various degrees of nastiness: • const_cast for getting write access to something declared const (§7.5) • static_cast for reversing a well-defined implicit conversion (§11.5 .2) • reinterpret_cast for changing the meaning of bit patterns (§11.5 .2) • dynamic_cast for dynamically checked class hierarchy navigation (§22.2 .1) • C-style casts, providing any of the named conversions and some combinations of those (§11.5.3) • Functional notation, providing a different notation for C-style casts (§11.5 .4) I have ordered these conversions in my order of preference and safety of use. Except for the {} construction notation, I can’t say I like any of those, but at least dynamic_cast is run-time checked. For conversion between two scalar numeric types, I tend to use a homemade explicit conversion function, narrow_cast, where a value might be narrowed:
ptg10564057 Section 11.5 Explicit Type Conversion 299 template<class Target, class Source> Ta r g et narrow_cast(Source v) { auto r = static_cast<Target>(v); // convert the value to the target type if (static_cast<Source>(r)!=v) throw runtime_error("narrow_cast<>() failed"); return r; } That is, if I can convert a value to the target type, convert the result back to the source type, and get back the original value, I’m happy with the result. That is a generalization of the rule the language applies to values in {} initialization (§6.3 .5 .2). For example: void test(double d, int i, char∗ p) { auto c1 = narrow_cast<char>(64); auto c2 = narrow_cast<char>(−64); // will throw if chars are unsigned auto c3 = narrow_cast<char>(264); // will throw if chars are 8-bit and signed auto d1 = narrow_cast<double>(1/3.0F); // OK auto f1 = narrow_cast<float>(1/3.0); // will probably throw auto c4 = narrow_cast<char>(i); // may throw auto f2 = narrow_cast<float>(d); // may throw auto p1 = narrow_cast<char∗>(i); // compile-time error auto i1 = narrow_cast<int>(p); // compile-time error auto d2 = narrow_cast<double>(i); // may throw (but probably will not) auto i2 = narrow_cast<int>(d); // may throw } Depending on your use of floating-point numbers, it may be worthwhile to use a range test for floating-point conversions, rather than !=. That is easily done using specializations (§25.3 .4.1) or type traits (§35.4.1). 11.5.1 Construction The construction of a value of type T from a value e can be expressed by the notation T{e} (§iso.8.5 .4). For example: auto d1 = double{2}; // d1==2.0 double d2 {double{2}/4}; // d1==0.5 Part of the attraction of the T{v} notation is that it will perform only ‘‘well-behaved’’ conversions. For example:
ptg10564057 300 Select Operations Chapter 11 void f(int); void f(double); void g(int i, double d) { f(i); // call f(int) f(double{i}); // error: {} doesn’t do int to floating conversion f(d); // call f(double) f(int{d}); // error: {} doesn’t truncate f(static_cast<int>(d)); // call f(int) with a truncated value f(round(d)); // call f(double) with a rounded value f(static_cast<int>(lround(d))); // call f(int) with a rounded value // if the d is overflows the int, this still truncates } I don’t consider truncation of floating-point numbers (e.g., 7.9 to 7) ‘‘well behaved,’’ so having to be explicit when you want it is a good thing. If rounding is desirable, we can use the standard- library function round(); it performs ‘‘conventional 4/5 rounding,’’ such as 7.9 to 8 and 7.4 to 7. It sometimes comes as a surprise that {}-construction doesn’t allow int to double conversion, but if (as is not uncommon) the size of an int is the same as the size of a double, then some such conver- sions must lose information. Consider: static_assert(sizeof(int)==sizeof(double),"unexpected sizes"); int x = numeric_limits<int>::max(); // largest possible integer double d = x; inty=x; We will not get x==y. However, we can still initialize a double with an integer literal that can be represented exactly. For example: double d { 1234 }; // fine Explicit qualification with the desired type does not enable ill-behaved conversions. For example: void g2(char∗ p) { int x = int{p}; // error: no char* to int conversion using Pint = int∗; int∗ p2 = Pint{p}; // error: no char* to int* conversion // ... } For T{v}, ‘‘reasonably well behaved’’ is defined as having a ‘‘non-narrowing’’ (§10.5) conversion from v to T or having an appropriate constructor for T (§17.3). The constructor notation T{} is used to express the default value of type T. For example:
ptg10564057 Section 11.5 .1 Construction 301 template<class T> void f(const T&); void g3() { f(int{}); // default int value f(complex<double>{}); // default complex value // ... } The value of an explicit use of the constructor for a built-in type is 0 converted to that type (§6.3 .5). Thus, int{} is another way of writing 0. For a user-defined type T, T{} is defined by the default con- structor (§3.2 .1 .1, §17.6), if any, otherwise by default construction, MT{}, of each member. Explicitly constructed unnamed objects are temporary objects, and (unless bound to a reference) their lifetime is limited to the full expression in which they are used (§6.4 .2). In this, they differ from unnamed objects created using new (§11.2). 11.5.2 Named Casts Some type conversions are not well behaved or easy to type check; they are not simple construc- tions of values from a well-defined set of argument values. For example: IO_device∗ d1 = reinterpret_cast<IO_device∗>(0Xff00); // device at 0Xff00 There is no way a compiler can know whether the integer 0Xff00 is a valid address (of an I/O device register). Consequently, the correctness of the conversions is completely in the hands of the pro- grammer. Explicit type conversion, often called casting, is occasionally essential. However, tradi- tionally it is seriously overused and a major source of errors. Another classical example of the need for explicit type conversion is dealing with ‘‘raw mem- ory,’’ that is, memory that holds or will hold objects of a type not known to the compiler. For example, a memory allocator (such as operator new(); §11.2.3) may return a void∗ pointing to newly allocated memory: void∗ my_allocator(size_t); void f() { int∗ p = static_cast<int∗>(my_allocator(100)); // new allocation used as ints // ... } A compiler does not know the type of the object pointed to by the void∗. The fundamental idea behind the named casts is to make type conversion more visible and to allow the programmer to express the intent of a cast: • static_cast converts between related types such as one pointer type to another in the same class hierarchy, an integral type to an enumeration, or a floating-point type to an integral type. It also does conversions defined by constructors (§16.2 .6, §18.3 .3, §iso.5.2 .9) and conversion operators (§18.4).
ptg10564057 302 Select Operations Chapter 11 • reinterpret_cast handles conversions between unrelated types such as an integer to a pointer or a pointer to an unrelated pointer type (§iso.5 .2 .10). • const_cast converts between types that differ only in const and volatile qualifiers (§iso.5.2 .11). • dynamic_cast does run-time checked conversion of pointers and references into a class hier- archy (§22.2 .1, §iso.5 .2 .7). These distinctions among the named casts allow the compiler to apply some minimal type checking and make it easier for a programmer to find the more dangerous conversions represented as reinter- pret_casts. Some static_casts are portable, but few reinterpret_casts are. Hardly any guarantees are made for reinterpret_cast, but generally it produces a value of a new type that has the same bit pat- tern as its argument. If the target has at least as many bits as the original value, we can reinter- pret_cast the result back to its original type and use it. The result of a reinterpret_cast is guaranteed to be usable only if its result is converted back to the exact original type. Note that reinterpret_cast is the kind of conversion that must be used for pointers to functions (§12.5). Consider: char x = 'a'; int∗ p1 = &x; // error: no implicit char* to int* conversion int∗ p2 = static_cast<int∗>(&x); // error: no implicit char* to int* conversion int∗ p3 = reinterpret_cast<int∗>(&x); // OK: on your head be it structB{/* ... */}; structD:B{/* ... */}; // see §3.2.2 and §20.5 .2 B∗pb=newD; // OK: implicit conversion from D* to B* D∗pd=pb; // error: no implicit conversion from B* to D* D∗ pd = static_cast<D∗>(pb); // OK Conversions among class pointers and among class reference types are discussed in §22.2 . If you feel tempted to use an explicit type conversion, take the time to consider if it is really necessary. In C++, explicit type conversion is unnecessary in most cases when C needs it (§1.3 .3) and also in many cases in which earlier versions of C++ needed it (§1.3 .2, §44.2.3). In many pro- grams, explicit type conversion can be completely avoided; in others, its use can be localized to a few routines. 11.5.3 C-Style Cast From C, C++ inherited the notation (T)e, which performs any conversion that can be expressed as a combination of static_casts, reinterpret_casts, const_casts to make a value of type T from the expression e (§44.2.3). Unfortunately, the C-style cast can also cast from a pointer to a class to a pointer to a private base of that class. Never do that, and hope for a warning from the compiler if you do it by mistake. This C-style cast is far more dangerous than the named conversion operators because the notation is harder to spot in a large program and the kind of conversion intended by the programmer is not explicit. That is, (T)e might be doing a portable conversion between related types, a nonportable conversion between unrelated types, or removing the const modifier from a pointer type. Without knowing the exact types of T and e, you cannot tell.
ptg10564057 Section 11.5 .4 Function-Style Cast 303 11.5.4 Function-Style Cast The construction of a value of type T from a value e can be expressed by the functional notation T(e). For example: void f(double d) { int i = int(d); // truncate d complex z = complex(d); // make a complex from d // ... } The T(e) construct is sometimes referred to as a function-style cast. Unfortunately, for a built-in type T, T(e) is equivalent to (T)e (§11.5 .3). This implies that for many built-in types T(e) is not safe. void f(double d, char∗ p) { int a = int(d); // truncates int b = int(p); // not portable // ... } Even explicit conversion of a longer integer type to a shorter (such as long to char) can result in nonportable implementation-defined behavior. Prefer T{v} conversions for well-behaved construction and the named casts (e.g ., static_cast) for other conversions. 11.6 Advice [1] Prefer prefix ++ over suffix ++; §11.1.4 . [2] Use resource handles to avoid leaks, premature deletion, and double deletion; §11.2 .1 . [3] Don’t put objects on the free store if you don’t have to; prefer scoped variables; §11.2 .1 . [4] Avoid ‘‘naked new’’ and ‘‘naked delete’’; §11.2 .1 . [5] Use RAII; §11.2 .1 . [6] Prefer a named function object to a lambda if the operation requires comments; §11.4 .2 . [7] Prefer a named function object to a lambda if the operation is generally useful; §11.4 .2. [8] Keep lambdas short; §11.4 .2 . [9] For maintainability and correctness, be careful about capture by reference; §11.4 .3 .1. [10] Let the compiler deduce the return type of a lambda; §11.4 .4. [11] Use the T{e} notation for construction; §11.5 .1 . [12] Avoid explicit type conversion (casts); §11.5 . [13] When explicit type conversion is necessary, prefer a named cast; §11.5 . [14] Consider using a run-time checked cast, such as narrow_cast<>(), for conversion between numeric types; §11.5 .
ptg10564057 This page intentionally left blank
ptg10564057 12 Functions Death to all fanatics! – Paradox • Function Declarations Why Functions?; Parts of a Function Declaration; Function Definitions; Returning Values; inline Functions; constexpr Functions; [[noreturn]] Functions; Local Variables • Argument Passing Reference Arguments; Array Arguments; List Arguments; Unspecified Number of Argu- ments; Default Arguments • Overloaded Functions Automatic Overload Resolution; Overloading and Return Type; Overloading and Scope; Resolution for Multiple Arguments; Manual Overload Resolution • Pre- and Postconditions • Pointer to Function • Macros Conditional Compilation; Predefined Macros; Pragmas • Advice 12.1 Function Declarations The main way of getting something done in a C++ program is to call a function to do it. Defining a function is the way you specify how an operation is to be done. A function cannot be called unless it has been previously declared. A function declaration gives the name of the function, the type of the value returned (if any), and the number and types of the arguments that must be supplied in a call. For example: Elem∗ next_elem(); // no argument; return an Elem* void exit(int); // int argument; return nothing double sqrt(double); // double argument; return a double
ptg10564057 306 Functions Chapter 12 The semantics of argument passing are identical to the semantics of copy initialization (§16.2 .6). Argument types are checked and implicit argument type conversion takes place when necessary. For example: double s2 = sqrt(2); // call sqrt() with the argument double{2} double s3 = sqrt("three"); // error: sqrt() requires an argument of type double The value of such checking and type conversion should not be underestimated. A function declaration may contain argument names. This can be a help to the reader of a pro- gram, but unless the declaration is also a function definition, the compiler simply ignores such names. As a return type, void means that the function does not return a value (§6.2 .7). The type of a function consists of the return type and the argument types. For class member functions (§2.3 .2, §16.2), the name of the class is also part of the function type. For example: double f(int i, const Info&); // type: double(int,const Info&) char& String::operator[](int); // type: char& String::(int) 12.1.1 Why Functions? There is a long and disreputable tradition of writing very long functions – hundreds of lines long. I once encountered a single (handwritten) function with more than 32,768 lines of code. Writers of such functions seem to fail to appreciate one of the primary purposes of functions: to break up com- plicated computations into meaningful chunks and name them. We want our code to be compre- hensible, because that is the first step on the way to maintainability. The first step to comprehensi- bility is to break computational tasks into comprehensible chunks (represented as functions and classes) and name those. Such functions then provide the basic vocabulary of computation, just as the types (built-in and user-defined) provide the basic vocabulary of data. The C++ standard algo- rithms (e.g ., find, sort, and iota) provide a good start (Chapter 32). Next, we can compose functions representing common or specialized tasks into larger computations. The number of errors in code correlates strongly with the amount of code and the complexity of the code. Both problems can be addressed by using more and shorter functions. Using a function to do a specific task often saves us from writing a specific piece of code in the middle of other code; making it a function forces us to name the activity and document its dependencies. Also, function call and return saves us from using error-prone control structures, such as gotos (§9.6) and contin- ues (§9.5.5). Unless they are very regular in structure, nested loops are an avoidable source of errors (e.g ., use a dot product to express a matrix algorithm rather than nesting loops; §40.6). The most basic advice is to keep a function of a size so that you can look at it in total on a screen. Bugs tend to creep in when we can view only part of an algorithm at a time. For many pro- grammers that puts a limit of about 40 lines on a function. My ideal is a much smaller size still, maybe an average of 7 lines. In essentially all cases, the cost of a function call is not a significant factor. Where that cost could be significant (e.g., for frequently used access functions, such as vector subscripting) inlining can eliminate it (§12.1 .5). Use functions as a structuring mechanism.
ptg10564057 Section 12.1 .2 Parts of a Function Declaration 307 12.1.2 Parts of a Function Declaration In addition to specifying a name, a set of arguments, and a return type, a function declaration can contain a variety of specifiers and modifiers. In all we can have: • The name of the function; required • The argument list, which may be empty (); required • The return type, which may be void and which may be prefix or suffix (using auto); required • inline, indicating a desire to have function calls implemented by inlining the function body (§12.1.5) • constexpr, indicating that it should be possible to evaluate the function at compile time if given constant expressions as arguments (§12.1 .6) • noexcept, indicating that the function may not throw an exception (§13.5 .1 .1) • A linkage specification, for example, static (§15.2) • [[noreturn]], indicating that the function will not return using the normal call/return mecha- nism (§12.1 .4) In addition, a member function may be specified as: • virtual, indicating that it can be overridden in a derived class (§20.3 .2) • override, indicating that it must be overriding a virtual function from a base class (§20.3 .4 .1) • final, indicating that it cannot be overriden in a derived class (§20.3.4 .2) • static, indicating that it is not associated with a particular object (§16.2 .12) • const, indicating that it may not modify its object (§3.2 .1 .1, §16.2 .9 .1) If you feel inclined to give readers a headache, you may write something like: struct S { [[noreturn]] virtual inline auto f(const unsigned long int ∗const) −> void const noexcept; }; 12.1.3 Function Definitions Every function that is called must be defined somewhere (once only; §15.2.3). A function defini- tion is a function declaration in which the body of the function is presented. For example: void swap(int∗, int∗); // a declaration void swap(int∗ p, int∗ q) // a definition { intt=∗p; ∗p=∗q; ∗q=t; } The definition and all declarations for a function must specify the same type. Unfortunately, to pre- serve C compatibility, a const is ignored at the highest level of an argument type. For example, this is two declarations of the same function: void f(int); // type is void(int) void f(const int); // type is void(int)
ptg10564057 308 Functions Chapter 12 That function, f(), could be defined as: void f(int x) { /*we can modify x here */ } Alternatively, we could define f() as: void f(const int x) { /*we cannot modify x here */ } In either case, the argument that f() can or cannot modify is a copy of what a caller provided, so there is no danger of an obscure modification of the calling context. Function argument names are not part of the function type and need not be identical in different declarations. For example: int& max(int& a, int& b, int& c); // return a reference to the larger of a, b, and c int& max(int& x1, int& x2, int& x3) { return (x1>x2)? ((x1>x3)?x1:x3) : ((x2>x3)?x2:x3); } Naming arguments in declarations that are not definitions is optional and commonly used to sim- plify documentation. Conversely, we can indicate that an argument is unused in a function defini- tion by not naming it. For example: void search(table∗ t, const char∗ key, const char∗) { // no use of the third argument } Typically, unnamed arguments arise from the simplification of code or from planning ahead for extensions. In both cases, leaving the argument in place, although unused, ensures that callers are not affected by the change. In addition to functions, there are a few other things that we can call; these follow most rules defined for functions, such as the rules for argument passing (§12.2): • Constructors (§2.3 .2, §16.2 .5) are technicallly not functions; in particular, they don’t return a value, can initialize bases and members (§17.4), and can’t have their address taken. • Destructors (§3.2.1 .2, §17.2) can’t be overloaded and can’t have their address taken. • Function objects (§3.4 .3, §19.2 .2) are not functions (they are objects) and can’t be over- loaded, but their operator()s are functions. • Lambda expressions (§3.4 .3, §11.4) are basically a shorthand for defining function objects. 12.1.4 Returning Values Every function declaration contains a specification of the function’s return type (except for con- structors and type conversion functions). Traditionally, in C and C++, the return type comes first in a function declaration (before the name of the function). However, a function declaration can also be written using a syntax that places the return type after the argument list. For example, the fol- lowing two declarations are equivalent: string to_string(int a); // prefix return type auto to_string(int a) −> string; // suffix return type
ptg10564057 Section 12.1 .4 Returning Values 309 That is, a prefix auto indicates that the return type is placed after the argument list. The suffix return type is preceded by −> . The essential use for a suffix return type comes in function template declarations in which the return type depends on the arguments. For example: template<class T, class U> auto product(const vector<T>& x, const vector<U>& y) −> decltype(x∗y); However, the suffix return syntax can be used for any function. There is an obvious similarity between the suffix return syntax for a function and the lambda expression syntax (§3.4 .3, §11.4); it is a pity those two constructs are not identical. A function that does not return a value has a ‘‘return type’’ of void. A value must be returned from a function that is not declared void (however, main() is special; see §2.2.1). Conversely, a value cannot be returned from a void function. For example: intf1(){} // error: no value returned void f2() { } // OK int f3() { return 1; } // OK void f4() { return 1; } // error: return value in void function int f5() { return; } // error: return value missing void f6() { return; } // OK A return value is specified by a return-statement. For example: int fac(int n) { return (n>1) ? n∗fac(n−1) : 1; } A function that calls itself is said to be recursive. There can be more than one return-statement in a function: int fac2(int n) { if(n>1) return n∗fac2(n−1); return 1; } Like the semantics of argument passing, the semantics of function value return are identical to the semantics of copy initialization (§16.2 .6). A return-statement initializes a variable of the returned type. The type of a return expression is checked against the type of the returned type, and all stan- dard and user-defined type conversions are performed. For example: double f() { return 1; } // 1 is implicitly converted to double{1} Each time a function is called, a new copy of its arguments and local (automatic) variables is cre- ated. The store is reused after the function returns, so a pointer to a local non-static variable should never be returned. The contents of the location pointed to will change unpredictably:
ptg10564057 310 Functions Chapter 12 int∗ fp() { int local = 1; // ... return &local; // bad } An equivalent error can occur when using references: int& fr() { int local = 1; // ... return local; // bad } Fortunately, a compiler can easily warn about returning references to local variables (and most do). There are no void values. However, a call of a void function may be used as the return value of a void function. For example: void g(int∗ p); void h(int∗ p) { // ... return g(p); // OK: equivalent to ‘‘g(p); return;’’ } This form of return is useful to avoid special cases when writing template functions where the return type is a template parameter. A return-statement is one of five ways of exiting a function: • Executing a return-statement. • ‘‘Falling off the end’’ of a function; that is, simply reaching the end of the function body. This is allowed only in functions that are not declared to return a value (i.e ., void functions) and in main(), where falling off the end indicates successful completion (§12.1 .4). • Throwing an exception that isn’t caught locally (§13.5). • Terminating because an exception was thrown and not caught locally in a noexcept function (§13.5.1 .1). • Directly or indirectly invoking a system function that doesn’t return (e.g ., exit(); §15.4). A function that does not return normally (i.e., through a return or ‘‘falling off the end’’) can be marked [[noreturn]] (§12.1 .7). 12.1.5 inline Functions A function can be defined to be inline. For example: inline int fac(int n) { return (n<2) ? 1 : n∗fac(n−1); }
ptg10564057 Section 12.1 .5 inline Functions 311 The inline specifier is a hint to the compiler that it should attempt to generate code for a call of fac() inline rather than laying down the code for the function once and then calling through the usual function call mechanism. A clever compiler can generate the constant 720 for a call fac(6). The possibility of mutually recursive inline functions, inline functions that recurse or not depending on input, etc., makes it impossible to guarantee that every call of an inline function is actually inlined. The degree of cleverness of a compiler cannot be legislated, so one compiler might generate 720, another 6∗fac(5), and yet another an un-inlined call fac(6). If you want a guarantee that a value is computed at compile time, declare it constexpr and make sure that all functions used in its evalua- tion are constexpr (§12.1 .6). To make inlining possible in the absence of unusually clever compilation and linking facilities, the definition – and not just the declaration – of an inline function must be in scope (§15.2). An inline specifier does not affect the semantics of a function. In particular, an inline function still has a unique address, and so do static variables (§12.1.8) of an inline function. If an inline function is defined in more than one translation unit (e.g., typically because it was defined in a header; §15.2 .2), its definition in the different translation units must be identical (§15.2.3). 12.1.6 constexpr Functions In general, a function cannot be evaluated at compile time and therefore cannot be called in a con- stant expression (§2.2 .3, §10.4). By specifying a function constexpr, we indicate that we want it to be usable in constant expressions if given constant expressions as arguments. For example: constexpr int fac(int n) { return (n>1) ? n∗fac(n−1) : 1; } constexpr int f9 = fac(9); // must be evaluated at compile time When constexpr is used in a function definition, it means ‘‘should be usable in a constant expres- sion when given constant expressions as arguments.’’ When used in an object definition, it means ‘‘evaluate the initializer at compile time.’’ For example: void f(int n) { int f5 = fac(5); // may be evaluated at compile time int fn = fac(n); // evaluated at run time (n is a variable) constexpr int f6 = fac(6); // must be evaluated at compile time constexpr int fnn = fac(n); // error: can’t guarantee compile-time evaluation (n is a variable) char a[fac(4)]; // OK: array bounds must be constants and fac() is constexpr char a2[fac(n)]; // error: array bounds must be constants and n is a variable // ... } To be evaluated at compile time, a function must be suitably simple: a constexpr function must
ptg10564057 312 Functions Chapter 12 consist of a single return-statement; no loops and no local variables are allowed. Also, a constexpr function may not have side effects. That is, a constexpr function is a pure function. For example: int glob; constexpr void bad1(int a) // error: constexpr function cannot be void { glob = a; // error: side effect in constexpr function } constexpr int bad2(int a) { if (a>=0) return a; else return −a; // error: if-statement in constexpr function } constexpr int bad3(int a) { sum=0; // error: local variable in constexpr function for (int i=0; i<a; +=i) sum +=fac(i); // error: loop in constexpr function return sum; } The rules for a constexpr constructor are suitably different (§10.4.3); there, only simple initial- ization of members is allowed. A constexpr function allows recursion and conditional expressions. This implies that you can express just about anything as a constexpr function if you really want to. However, you’ll find the debugging gets unnecessarily difficult and compile times longer than you would like unless you restrict the use of constexpr functions to the relatively simple tasks for which they are intended. By using literal types (§10.4 .3), constexpr functions can be defined to use user-defined types. Like inline functions, constexpr functions obey the ODR (‘‘one-definition rule’’), so that defini- tions in the different translation units must be identical (§15.2 .3). You can think of constexpr func- tions as a restricted form of inline functions (§12.1 .5). 12.1 .6 .1 constexpr and References A constexpr function cannot have side effects, so writing to nonlocal objects is not possible. How- ever, a constexpr function can refer to nonlocal objects as long as it does not write to them. constexpr int ftbl[] { 1, 2, 3, 5, 8, 13 }; constexpr int fib(int n) { return (n<sizeof(ftbl)/sizeof(∗ftbl)) ? ftbl[n] : fib(n); } A constexpr function can take reference arguments. Of course, it cannot write through such refer- ences, but const reference parameters are as useful as ever. For example, in the standard library (§40.4) we find:
ptg10564057 Section 12.1 .6 .1 constexpr and References 313 template<> class complex<float> { public: // ... explicit constexpr complex(const complex<double>&); // ... }; This allows us to write: constexpr complex<float> z {2.0}; The temporary variable that is logically constructed to hold the const reference argument simply becomes a value internal to the compiler. It is possible for a constexpr function to return a reference or a pointer. For example: constexpr const int∗ addr(const int& r) { return &r; } // OK However, doing so brings us away from the fundamental role of constexpr functions as parts of con- stant expression evaluation. In particular, it can be quite tricky to determine whether the result of such a function is a constant expression. Consider: static const int x = 5; constexpr const int∗ p1 = addr(x); // OK constexpr int xx = ∗p1; // OK static int y; constexpr const int∗ p2 = addr(y); // OK constexpr int yy = ∗y; // error: attempt to read a variable constexpr const int∗ tp = addr(5); // error: address of temporary 12.1 .6 .2 Conditional Evaluation A branch of a conditional expression that is not taken in a constexpr function is not evaluated. This implies that a branch not taken can require run-time evaluation. For example: constexpr int check(int i) { return (low<=i && i<high) ? i : throw out_of_range(); } constexpr int low = 0; constexpr int high = 99; // ... constexpr int val = check(f(x,y,z)); You might imagine low and high to be configuration parameters that are known at compile time, but not at design time, and that f(x,y,z) computes some implementation-dependent value.
ptg10564057 314 Functions Chapter 12 12.1.7 [[noreturn]] Functions A construct [[...]] is called an attribute and can be placed just about anywhere in the C++ syntax. In general, an attribute specifies some implementation-dependent property about the syntactic entity that precedes it. In addition, an attribute can be placed in front of a declaration. There are only two standard attributes (§iso.7 .6), and [[noreturn]] is one of them. The other is [[carries_depen- dency]] (§41.3). Placing [[noreturn]] at the start of a function declaration indicates that the function is not expected to return. For example: [[noreturn]] void exit(int); // exit will never return Knowing that a function does not return is useful for both comprehension and code generation. What happens if the function returns despite a [[noreturn]] attribute is undefined. 12.1.8 Local Variables A name defined in a function is commonly referred to as a local name. A local variable or constant is initialized when a thread of execution reaches its definition. Unless declared static, each invoca- tion of the function has its own copy of the variable. If a local variable is declared static, a single, statically allocated object (§6.4 .2) will be used to represent that variable in all calls of the function. It will be initialized only the first time a thread of execution reaches its definition. For example: void f(int a) { while (a−−) { static int n = 0; // initialized once intx=0; // initialized ’a’ times in each call of f() cout<<"n=="<<n++<<",x=="<<x++<<'\n'; } } int main() { f(3); } This prints: n==0,x==0 n==1,x==0 n==2,x==0 A static local variable allows the function to preserve information between calls without introduc- ing a global variable that might be accessed and corrupted by other functions (see also §16.2 .12). Initialization of a static local variable does not lead to a data race (§5.3 .1) unless you enter the function containing it recursively or a deadlock occurs (§iso.6 .7). That is, the C++ implementation must guard the initialization of a local static variable with some kind of lock-free construct (e.g ., a call_once; §42.3.3). The effect of initializing a local static recursively is undefined. For example:
ptg10564057 Section 12.1 .8 Local Variables 315 int fn(int n) { static int n1 = n; // OK static int n2 = fn(n−1)+1; // undefined return n; } A static local variable is useful for avoiding order dependencies among nonlocal variables (§15.4.1). There are no local functions; if you feel you need one, use a function object or a lambda expres- sion (§3.4.3, §11.4). The scope of a label (§9.6), should you be foolhardy enough to use one, is the complete func- tion, independent of which nested scope it may be in. 12.2 Argument Passing When a function is called (using the suffix (), known as the call operator or application operator), store is set aside for its formal arguments (also known as its parameters), and each formal argu- ment is initialized by its corresponding actual argument. The semantics of argument passing are identical to the semantics of initialization (copy initialization, to be precise; §16.2 .6). In particular, the type of an actual argument is checked against the type of the corresponding formal argument, and all standard and user-defined type conversions are performed. Unless a formal argument (parameter) is a reference, a copy of the actual argument is passed to the function. For example: int∗ find(int∗ first, int∗ last, int v) // find x in [first:last) { while (first!=last && ∗first!=v) ++first; return first; } void g(int∗ p, int∗ q) { int∗ pp = find(p,q,'x'); // ... } Here, the caller’s copy of the argument, p, is not modified by the operations on find()’s copy, called first. The pointer is passed by value. There are special rules for passing arrays (§12.2.2), a facility for passing unchecked arguments (§12.2.4), and a facility for specifying default arguments (§12.2 .5). The use of initializer lists is described in §12.2 .3 and the ways of passing arguments to template functions in §23.5 .2 and §28.6 .2 .
ptg10564057 316 Functions Chapter 12 12.2.1 Reference Arguments Consider: void f(int val, int& ref) { ++val; ++ref; } When f() is called, ++val increments a local copy of the first actual argument, whereas ++ref incre- ments the second actual argument. Consider: void g() { inti=1; intj=1; f(i,j); } The call f(i,j) will increment j but not i. The first argument, i, is passed by value; the second argu- ment, j, is passed by reference. As mentioned in §7.7, functions that modify call-by-reference argu- ments can make programs hard to read and should most often be avoided (but see §18.2.5). It can, however, be noticeably more efficient to pass a large object by reference than to pass it by value. In that case, the argument might be declared a const reference to indicate that the reference is used for efficiency reasons only and not to enable the called function to change the value of the object: void f(const Large& arg) { // the value of ‘‘arg’’ cannot be changed // (except by using explicit type conversion; §11.5) } The absence of const in the declaration of a reference argument is taken as a statement of intent to modify the variable: void g(Large& arg); // assume that g() modifies arg Similarly, declaring a pointer argument const tells readers that the value of an object pointed to by that argument is not changed by the function. For example: int strlen(const char∗); // number of characters in a C-style string char∗ strcpy(char∗ to, const char∗ from); // copy a C-style string int strcmp(const char∗, const char∗); // compare C-style strings The importance of using const arguments increases with the size of a program. Note that the semantics of argument passing are different from the semantics of assignment. This is important for const arguments, reference arguments, and arguments of some user-defined types. Following the rules for reference initialization, a literal, a constant, and an argument that requires conversion can be passed as a const T& argument, but not as a plain (non-const) T& argu- ment. Allowing conversions for a const T& argument ensures that such an argument can be given
ptg10564057 Section 12.2 .1 Reference Arguments 317 exactly the same set of values as a T argument by passing the value in a temporary, if necessary. For example: float fsqrt(const float&); // Fortran-style sqrt taking a reference argument void g(double d) { float r = fsqrt(2.0f); // pass reference to temp holding 2.0f r = fsqrt(r); // pass reference to r r = fsqrt(d); // pass reference to temp holding static_cast<float>(d) } Disallowing conversions for non-const reference arguments (§7.7) avoids the possibility of silly mistakes arising from the introduction of temporaries. For example: void update(float& i); void g(double d, float r) { update(2.0f); // error: const argument update(r); // pass reference to r update(d); // error: type conversion required } Had these calls been allowed, update() would quietly have updated temporaries that immediately were deleted. Usually, that would come as an unpleasant surprise to the programmer. If we wanted to be precise, pass-by-reference would be pass-by-lvalue-reference because a function can also take rvalue references. As described in §7.7, an rvalue can be bound to an rvalue reference (but not to an lvalue reference) and an lvalue can be bound to an lvalue reference (but not to an rvalue reference). For example: void f(vector<int>&); // (non-const) lvalue reference argument void f(const vector<int>&); // const lvalue reference argument void f(vector<int>&&); // rvalue reference argument void g(vector<int>& vi, const vector<int>& cvi) { f(vi); // call f(vector<int>&) f(vci); // call f(const vector<int>&) f(vector<int>{1,2,3,4}); // call f(vector<int>&&); } We must assume that a function will modify an rvalue argument, leaving it good only for de- struction or reassignment (§17.5). The most obvious use of rvalue references is to define move constructors and move assignments (§3.3 .2, §17.5 .2). I’m sure someone will find a clever use for const-rvalue-reference arguments, but so far, I have not seen a genuine use case. Please note that for a template argument T, the template argument type deduction rules give T&& a significantly different meaning from X&& for a type X (§23.5 .2.1). For template arguments, an rvalue reference is most often used to implement ‘‘perfect forwarding’’ (§23.5 .2 .1, §28.6 .3).
ptg10564057 318 Functions Chapter 12 How do we choose among the ways of passing arguments? My rules of thumb are: [1] Use pass-by-value for small objects. [2] Use pass-by-const-reference to pass large values that you don’t need to modify. [3] Return a result as a return value rather than modifying an object through an argument. [4] Use rvalue references to implement move (§3.3 .2, §17.5 .2) and forwarding (§23.5 .2 .1). [5] Pass a pointer if ‘‘no object’’ is a valid alternative (and represent ‘‘no object’’ by nullptr). [6] Use pass-by-reference only if you have to. The ‘‘when you have to’’ in the last rule of thumb refers to the observation that passing pointers is often a less obscure mechanism for dealing with objects that need modification (§7.7.1, §7.7 .4) than using references. 12.2.2 Array Arguments If an array is used as a function argument, a pointer to its initial element is passed. For example: int strlen(const char∗); void f() { char v[] = "Annemarie"; int i = strlen(v); int j = strlen("Nicholas"); } That is, an argument of type T[] will be converted to a T∗ when passed as an argument. This implies that an assignment to an element of an array argument changes the value of an element of the argu- ment array. In other words, arrays differ from other types in that an array is not passed by value. Instead, a pointer is passed (by value). A parameter of array type is equivalent to a parameter of pointer type. For example: void odd(int∗ p); void odd(int a[]); void odd(int buf[1020]); These three declarations are equivalent and declare the same function. As usual, the argument names do not affect the type of the function (§12.1 .3). The rules and techniques for passing multi- dimensional arrays can be found in §7.4 .3 . The size of an array is not available to the called function. This is a major source of errors, but there are several ways of circumventing this problem. C-style strings are zero-terminated, so their size can be computed (e.g ., by a potentially expensive call of strlen(); §43.4). For other arrays, a second argument specifying the size can be passed. For example: void compute1(int∗ vec_ptr, int vec_size); // one way At best, this is a workaround. It is usually preferable to pass a reference to some container, such as vector (§4.4 .1, §31.4), array (§34.2 .1), or map (§4.4 .3, §31.4 .3). If you really want to pass an array, rather than a container or a pointer to the first element of an array, you can declare a parameter of type reference to array. For example:
ptg10564057 Section 12.2 .2 Array Arguments 319 void f(int(&r)[4]); void g() { int a1[] = {1,2,3,4}; int a2[] = {1,2}; f(a1); // OK f(a2); // error : wrong number of elements } Note that the number of elements is part of a reference-to-array type. That makes such references far less flexible than pointers and containers (such as vector). The main use of references to arrays is in templates, where the number of elements is then deduced. For example: template<class T, int N> void f(T(&r)[N]) { // ... } int a1[10]; double a2[100]; void g() { f(a1); //Tisint;Nis10 f(a2); //Tisdouble;Nis100 } This typically gives rise to as many function definitions as there are calls to f() with distinct array types. Multidimensional arrays are tricky (see §7.3), but often arrays of pointers can be used instead, and they need no special treatment. For example: const char∗ day[] = { "mon", "tue", "wed", "thu", "fri", "sat", "sun" }; As ever, vector and similar types are alternatives to the built-in, low-level arrays and pointers. 12.2.3 List Arguments A {}-delimited list can be used as an argument to a parameter of: [1] Type std::initializer_list<T>, where the values of the list can be implicitly converted to T [2] A type that can be initialized with the values provided in the list [3] A reference to an array of T, where the values of the list can be implicitly converted to T Technically, case [2] covers all examples, but I find it easier to think of the three cases separately. Consider:
ptg10564057 320 Functions Chapter 12 template<class T> void f1(initializer_list<T>); struct S { int a; string s; }; void f2(S); template<class T, int N> void f3(T (&r)[N]); void f4(int); void g() { f1({1,2,3,4}); // T is int and the initializer_list has size() 4 f2({1,"MKS"}); // f2(S{1,"MKS"}) f3({1,2,3,4}); // T is int and N is 4 f4({1}); // f4(int{1}); } If there is a possible ambiguity, an initializer_list parameter takes priority. For example: template<class T> void f(initializer_list<T>); struct S { int a; string s; }; void f(S); template<class T, int N> void f(T (&r)[N]); void f(int); void g() { f({1,2,3,4}); // T is int and the initializer_list has size() 4 f({1,"MKS"}); // calls f(S) f({1}); // T is int and the initializer_list has size() 1 } The reason that a function with an initializer_list argument take priority is that it could be very con- fusing if different functions were chosen based on the number of elements of a list. It is not possi- ble to eliminate every form of confusion in overload resolution (for example, see §4.4, §17.3 .4 .1), but giving initializer_list parameters priority for {}-list arguments seems to minimize confusion.
ptg10564057 Section 12.2 .3 List Arguments 321 If there is a function with an initializer-list argument in scope, but the argument list isn’t a match for that, another function can be chosen. The call f({1,"MKS"}) was an example of that. Note that these rules apply to std::initializer_list<T> arguments only. There are no special rules for std::initializer_list<T>& or for other types that just happen to be called initializer_list (in some other scope). 12.2.4 Unspecified Number of Arguments For some functions, it is not possible to specify the number and type of all arguments expected in a call. To implement such interfaces, we have three choices: [1] Use a variadic template (§28.6): this allows us to handle an arbitrary number of arbitrary types in a type-safe manner by writing a small template metaprogram that interprets the argument list to determine its meaning and take appropriate actions. [2] Use an initializer_list as the argument type (§12.2.3). This allows us to handle an arbitrary number of arguments of a single type in a type-safe manner. In many contexts, such homogeneous lists are the most common and important case. [3] Terminate the argument list with the ellipsis (...), which means ‘‘and maybe some more arguments.’’ This allows us to handle an arbitrary number of (almost) arbitrary types by using some macros from <cstdarg>. This solution is not inherently type-safe and can be hard to use with sophisticated user-defined types. However, this mechanism has been used from the earliest days of C. The first two mechanisms are described elsewhere, so I describe only the third mechanism (even though I consider it inferior to the others for most uses). For example: int printf(const char∗ ...); This specifies that a call of the standard-library function printf() (§43.3) must have at least one argu- ment, a C-style string, but may or may not have others. For example: printf("Hello, world!\n"); printf("My name is %s %s\n", first_name, second_name); printf("%d + %d = %d\n",2,3,5); Such a function must rely on information not available to the compiler when interpreting its argu- ment list. In the case of printf(), the first argument is a format string containing special character sequences that allow printf() to handle other arguments correctly; %s means ‘‘expect a char∗ argu- ment’’ and %d means ‘‘expect an int argument.’’ However, the compiler cannot in general ensure that the expected arguments are really provided in a call or that an argument is of the expected type. For example: #include <cstdio> int main() { std::printf("My name is %s %s\n",2); } This is not valid code, but most compilers will not catch this error. At best, it will produce some strange-looking output (try it!).
ptg10564057 322 Functions Chapter 12 Clearly, if an argument has not been declared, the compiler does not have the information needed to perform the standard type checking and type conversion for it. In that case, a char or a short is passed as an int and a float is passed as a double. This is not necessarily what the program- mer expects. A well-designed program needs at most a few functions for which the argument types are not completely specified. Overloaded functions, functions using default arguments, functions taking initializer_list arguments, and variadic templates can be used to take care of type checking in most cases when one would otherwise consider leaving argument types unspecified. Only when both the number of arguments and the types of arguments vary and a variadic template solution is deemed undesirable is the ellipsis necessary. The most common use of the ellipsis is to specify an interface to C library functions that were defined before C++ provided alternatives: int fprintf(FILE∗, const char∗ ...); // from <cstdio> int execl(const char∗ ...); // from UNIX header A standard set of macros for accessing the unspecified arguments in such functions can be found in <cstdarg>. Consider writing an error function that takes one integer argument indicating the sever- ity of the error followed by an arbitrary number of strings. The idea is to compose the error mes- sage by passing each word as a separate C-style string argument. The list of string arguments should be terminated by the null pointer: extern void error(int ...); extern char∗ itoa(int, char[]); // int to alpha int main(int argc, char∗ argv[]) { switch (argc) { case 1: error(0,argv[0],nullptr); break; case 2: error(0,argv[0],