A Tour of C++ The C++ In-Depth Series BJARNE STROUSTRUP, Editor ‘‘I have made this letter longer than usual, because I lack the time to make it short.’’ — Blaise Pascal The C++ In-Depth Series is a collection of concise and focused books providing real-world pro- grammers with reliable information about the C++ programming language. Selected by the designer and original implementer of C++, Bjarne Stroustrup, and written by experts in the field, each book in this series presents either a single topic, at a technical level appropriate to that topic, or a fast-paced overview, for a quick understanding of broader language features. Its practical approach, in either case, is designed to lift professionals (and aspiring professionals) to the next level of programming skill or knowledge. These short books are meant to be read and referenced without the distraction of unrelated material.
As C++ matures, it becomes increasingly important to be able to separate essential infor- mation from hype and glitz, and to find the deep content and practical guidance needed for contin- ued development. The C++ In-Depth Series provides the background, tools, concepts, techniques, and new approaches that can enable this development, and thereby give readers a valuable, critical edge. A Tour of C++ Bjarne Stroustrup Upper Saddle River, NJ • Boston • Indianapolis • San Francisco New York • Toronto • Montreal • London • Munich • Paris • Madrid Capetown • Sydney • Tokyo • Singapore • Mexico City 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.
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. A Tour of C++ / Bjarne Stroustrup. pages cm Includes bibliographical references and index. paper)—ISBN 0-321-958314 (pbk.13’3—dc23 2013002159 Copyright © 2014 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-958310 ISBN-10: 0-321-958314 Text printed in the United States on recycled paper at Edwards Brothers Malloy in Ann Arbor, Michigan. First printing, September 2013 Contents Contents v Preface ix 1 The Basics 1 1.5 Types, Variables, and Arithmetic .8 Pointers, Arrays, and References. 14 2 User-Defined Types 15 2.
21 vi Contents 3 Modularity 23 3.6 Copy and Move .4 Concepts and Generic Programming .8 Template Compilation Model .2 Standard-Library Components .3 Standard-Library Headers and Namespace. 74 7 Strings and Regular Expressions 75 7.5 I/O of User-Defined Types .2 Use of Iterators. 131 viii Contents 12 Numerics 133 12.2 Tasks and threads .6 Waiting for Events. 151 14 History and Compatibility 153 14.
168 Index 171 Preface When you wish to instruct, be brief. – Cicero 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.
Like other modern languages, C++ is large and there are a large number of libraries needed for effective use. This thin book aims to give an experienced programmer an idea of what constitutes modern C++. It covers most major language features and the major standard-library components. This book can be read in just a few hours but, obviously, there is much more to writing good C++ than can be learned in a day.
However, the aim here is not mastery, but to give an overview, to give key examples, and to help a programmer get started. For mastery, consider my The C++ Program- ming Language, Fourth Edition (TC++PL4) [Stroustrup,2013]. In fact, this book is an extended version of the material that constitutes Chapters 2-5 of TC++PL4, also entitled A Tour of C++. I have added extensions and improvements to make this book reasonably self-contained.
The struc- ture of this tour follows that of TC++PL4, so it is easy to find supplementary material. Similarly, the exercises for TC++PL4 that are available on my Web site (www.com) can be used to support this tour. 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. 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. You do not know how to navigate the formal and informal rules that govern life in the city. To really know a city, you have to live in it, x Preface 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 the major C++ language features as they support programming styles, such as object-oriented and generic programming. It does not attempt to provide a detailed, reference-man- ual, feature-by-feature view of the language. Similarly, it presents the standard libraries in terms of examples, rather than exhaustively.
It does not describe libraries beyond those defined by the ISO standard. The reader can search out supporting material as needed. [Stroustrup,2009] and [Strous- trup,2012] are examples of such material, but there is an enormous amount of material (of varying quality) available on the Web. For example, when I mention a standard library function or class, its definition can easily be looked up, and by examining the documentation of its header (also easily accessible on the Web), many related facilities can be found.
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 infor- mation can be found in Chapter 14 (History and Compatibility). Acknowledgments Much of the material presented here is borrowed from TC++PL4 [Stroustrup,2012], so thanks to all who helped completing that book.
Also, thanks to my editor at Addison-Wesley, Peter Gordon, who first suggested that the four Tour chapters from TC++PL4 might be expanded into a reason- ably self-contained and consistent publication of their own. College Station, Texas Bjarne Stroustrup 1 The Basics The first thing we do, let’s kill all the language lawyers. – Henry VI, Part II • Introduction • Programs • Hello, World! • Functions • Types, Variables, and Arithmetic • Scope and Lifetime • Constants • Pointers, Arrays, and References • Tests • Advice 1.1 Introduction 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 language facilities supporting the styles most often seen in C and sometimes called procedural programming.2 Programs 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). 2 The Basics Chapter 1 source file 1 compile object file 1 link executable file source file 2 compile object file 2 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., char and int) and loops (e., for-state- ments and while-statements) • Standard-library components, such as containers (e., vector and map) and I/O operations (e., << 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., 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.3 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. 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"; } Section 1.3 Hello, World! 3 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 (§3.