The C++ Programming Language 3rd Ed

This book introduces standard C++ and the key programming and design techniques supported by C++.


Bjarne Stroustrup


1022 Pages

82105 Reads

79 Downloads

English

PDF Format

3.38 MB

C, C++ Programming

Download PDF format


  • Bjarne Stroustrup    
  • 1022 Pages   
  • 03 Mar 2015
  • Page - 1

    read more..

  • Page - 2

    The C+ + Programming Language Third Edition Bjarne Stroustrup AT&T Labs Murray Hill, New Jersey Addison-Wesley An Imprint of Addison Wesley Longman, Inc. Reading, Massachusetts • Harlow, England • Menlo Park, California Berkeley, California • Don Mills, Ontario • Sydney Bonn • Amsterdam • Tokyo • Mexico City read more..

  • Page - 3

    ii 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 Addison-Wesley was aware of a trademark claim, the designations have been printed in initial capital letters or all capital letters The author and publisher have taken care in the preparation of this book, but make read more..

  • Page - 4

    Contents Contents iii Preface v Preface to Second Edition vii Preface to First Edition ix Introductory Material 1 1 Notes to the Reader ..................................................................... 3 2 A Tour of C++ ............................................................................. 21 3 A Tour of the Standard Library .................................................. 45 Part I: Basic Facilities read more..

  • Page - 5

    iv Contents Part II: Abstraction Mechanisms 221 10 Classes ........................................................................................ 223 11 Operator Overloading ................................................................. 261 12 Derived Classes ........................................................................... 301 13 Templates .................................................................................... 327 14 read more..

  • Page - 6

    Preface 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, read more..

  • Page - 7

    vi Preface 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. 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++ read more..

  • Page - 8

    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 read more..

  • Page - 9

    viii Preface to the Second Edition clearly than they would in a fully elaborated program, where they would be buried in details. Most 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 read more..

  • Page - 10

    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 read more..

  • Page - 11

    x 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 read more..

  • Page - 12

    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++, read more..

  • Page - 13

    2 Introduction Introduction ‘‘... 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 read more..

  • Page - 14

    _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 1 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Notes to the Reader "The time has come," the Walrus read more..

  • Page - 15

    4 Notes to the Reader Chapter 1 C++ language. If nothing else, these chapters should convince you that C++ isn’t (just) C and that C++ has come a long way since the first and second editions of this book. Chapter 2 gives a high- level acquaintance with C++. The discussion focuses on the language features supporting data abstraction, object-oriented programming, and generic read more..

  • Page - 16

    Section 1.1.1 Examples and References 5 1.1.1 Examples and References This book emphasizes program organization rather than the writing 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, read more..

  • Page - 17

    6 Notes to the Reader Chapter 1 1.1.2 Exercises Exercises are found at the ends of chapters. The exercises are mainly of the write-a-program vari- ety. Always write enough code for a solution to be compiled and run with at least a few test cases. The exercises vary considerably in difficulty, so they are marked with an estimate of their diffi- culty. The scale is read more..

  • Page - 18

    Section 1.2 Learning C++ 7 However, ideas must be transformed into something that fits with the general structure and type system of C++ in order to be effective in the different context. Over the basic type system of a lan- guage, only Pyrrhic victories are possible. C++ supports a gradual approach to learning. How you approach learning a new programming language depends on read more..

  • Page - 19

    8 Notes to the Reader Chapter 1 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 described in Part III 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 read more..

  • Page - 20

    Section 1.3.1 Efficiency and Structure 9 when breaking every rule of good style. For a larger program, this is simply not so. If the structure of a 100,000-line program is bad, you will find that new errors are introduced as fast as old ones are removed. C++ was designed to enable larger programs to be structured in a rational way so that it would be reasonable for a read more..

  • Page - 21

    10 Notes to the Reader Chapter 1 1.4 Historical Note I invented C++, wrote its early definitions, and produced its first implementation. I chose and for- mulated the design criteria for C++, designed all its major facilities, and was responsible for the processing of extension proposals in the C++ standards committee. Clearly, C++ owes much to C [Kernighan,1978]. Except for closing read more..

  • Page - 22

    Section 1.4 Historical Note 11 C, or various modern 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, read more..

  • Page - 23

    12 Notes to the Reader Chapter 1 1.5 Use of C++ C++ is used by hundreds of thousands of programmers in essentially every application domain. This use is supported by about a dozen independent implementations, hundreds of libraries, hun- dreds of textbooks, several technical journals, many conferences, and innumerable consultants. Training and education at a variety of levels are read more..

  • Page - 24

    Section 1.5 Use of C++ 13 – available enough for organizations and collaborations relying on diverse development and execution environments, – comprehensive enough to be a vehicle for teaching advanced concepts and techniques, and – commercial enough to be a vehicle for putting what is learned into non-academic use. C++ is a language that you can grow with. 1.6 C and C++ C read more..

  • Page - 25

    14 Notes to the Reader Chapter 1 C Programming Language (2nd Edition) [Kernighan,1988], is a C++ program. Experience with any statically typed language will be a help when learning C++. 1.6.1 Suggestions for C Programmers The better one knows C, the harder it seems to be to avoid writing C++ in C style, thereby losing some of the potential benefits of C++. Please take a read more..

  • Page - 26

    Section 1.7 Thinking about Programming in C++ 15 1.7 Thinking about Programming in C++ Ideally, you approach the task of designing a program in three stages. First, you gain a clear under- standing of the problem (analysis), then you identify the key concepts involved in a solution (design), and finally you express that solution in a program (programming). However, the details of read more..

  • Page - 27

    16 Notes to the Reader Chapter 1 One of the best tools for untangling dependency graphs is the clean separation of interface and implementation. Abstract classes (§2.5.4, §12.3) are C++’s primary tool for doing that. Another form of commonality can be expressed through templates (§2.7, Chapter 13). A class template specifies a family of classes. For example, a list template read more..

  • Page - 28

    Section 1.8 Advice 17 More specific or detailed rules of thumb can be found in the ‘‘Advice’’ section of each chapter. Remember, this advice is only rough rules of thumb, not immutable laws. A piece of advice should be applied only ‘‘where reasonable.’’ There is no substitute for intelligence, experience, common sense, and good taste. I find rules of the form read more..

  • Page - 29

    18 Notes to the Reader Chapter 1 [Griswold,1970] R. E. Griswold, et al.: The Snobol4 Programming Language. Prentice-Hall. Englewood Cliffs, New Jersey. 1970. [Griswold,1983] R. E. Griswold and M. T. Griswold: The ICON Programming Language. Prentice-Hall. Englewood Cliffs, New Jersey. 1983. [Hamilton,1993] G. Hamilton and P. Kougiouris: The Spring Nucleus: A Microkernel for Objects. Proc. 1993 read more..

  • Page - 30

    Section 1.8.1 References 19 [Stroustrup,1986] Bjarne Stroustrup: The C++ Programming Language. Addison-Wesley. Reading, Mass. 1986. ISBN 0-201-12078-X. [Stroustrup,1987] Bjarne Stroustrup and Jonathan Shopiro: A Set of C Classes for Co-Routine Style Programming. Proc. USENIX C++ Conference. Santa Fe, New Mexico. November 1987. [Stroustrup,1991] Bjarne Stroustrup: The C++ Programming Language (Second read more..

  • Page - 31

    20 Notes to the Reader Chapter 1 The C++ Programming Language, Special Edition by Bjarne Stroustrup. Copyright ©2000 by AT&T. Published by Addison Wesley, Inc. ISBN 0-201-70073-5. All rights reserved. read more..

  • Page - 32

    _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 2 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ A Tour of C+ + The first thing we do, let´s kill all read more..

  • Page - 33

    22 A Tour of C++ Chapter 2 2.2 Programming Paradigms [tour.paradigm] Object-oriented programming is a technique for programming – a paradigm for writing ‘‘good’’ programs for a set of problems. If the term ‘‘object-oriented programming language’’ means any- thing, it must mean a programming language that provides mechanisms that support the object- oriented style of programming read more..

  • Page - 34

    Section 2.3 Procedural Programming 23 2.3 Procedural Programming [tour.proc] The original programming paradigm is: Decide which procedures you want; use the best algorithms you can find. The focus is on the processing – the algorithm needed to perform the desired computation. Lan- guages support this paradigm by providing facilities for passing arguments to functions and return- ing read more..

  • Page - 35

    24 A Tour of C++ Chapter 2 b bo oo ol l / / Boolean, possible values are true and false c ch ha ar r / / character, for example, ’a’, ’z’, and ’9’ i in nt t / / integer, for example, 1, 42, and 1216 d do ou ub bl le e / / double-precision floating-point number, for example, 3.14 and 299793.0 A c ch ha ar r variable is of the natural size to hold a read more..

  • Page - 36

    Section 2.3.2 Tests and Loops 25 The << operator (‘‘put to’’) is used as an output operator; c co ou ut t is the standard output stream. The >> operator (‘‘get from’’) is used as an input operator; c ci in n is the standard input stream. The type of the right-hand operand of >> determines what input is accepted and is the target of the input read more..

  • Page - 37

    26 A Tour of C++ Chapter 2 2.3.3 Pointers and Arrays [tour.ptr] An array can be declared like this: c ch ha ar r v v[1 10 0] ; / / array of 10 characters Similarly, a pointer can be declared like this: c ch ha ar r* p p; / / pointer to character In declarations, [] means ‘‘array of’’ and * means ‘‘pointer to.’’ All arrays have 0 0 as their lower read more..

  • Page - 38

    Section 2.4 Modular Programming 27 C++ provides a mechanism for grouping related data, functions, etc., into separate namespaces. For example, the user interface of a S St ta ac ck k module could be declared and used like this: n na am me es sp pa ac ce e S St ta ac ck k { / / interface v vo oi id d p pu us sh h(c ch ha ar r) ; c ch ha ar r p read more..

  • Page - 39

    28 A Tour of C++ Chapter 2 # i in nc cl lu ud de e " s st ta ac ck k.h h" / / get the interface v vo oi id d f f() { S St ta ac ck k: : p pu us sh h(´c c´) ; i if f ( S St ta ac ck k: : p po op p() != ´ c c´) e er rr ro or r("i im mp po os ss si ib bl le e") ; } To help the compiler ensure consistency, read more..

  • Page - 40

    Section 2.4.2 Exception Handling 29 the operation rather than on the module that found the error while trying to perform the operation. As programs grow, and especially when libraries are used extensively, standards for handling errors (or, more generally, ‘‘exceptional circumstances’’) become important. Consider again the S St ta ac ck k example. What ought to be done when we read more..

  • Page - 41

    30 A Tour of C++ Chapter 2 2.5 Data Abstraction [tour.da] Modularity is a fundamental aspect of all successful large programs. It remains a focus of all design discussions throughout this book. However, modules in the form described previously are not sufficient to express complex systems cleanly. Here, I first present a way of using modules to provide a form of user-defined read more..

  • Page - 42

    Section 2.5.1 Modules Defining Types 31 We could implement this S St ta ac ck k in several ways. It is important that a user doesn’t need to know how we do it. As long as we keep the interface unchanged, a user will not be affected if we decide to re-implement S St ta ac ck k. An implementation might preallocate a few stack representations and let S St ta read more..

  • Page - 43

    32 A Tour of C++ Chapter 2 2.5.2 User-Defined Types [tour.udt] C++ attacks this problem by allowing a user to directly define types that behave in (nearly) the same way as built-in types. Such a type is often called an abstract data type. I prefer the term user-defined type. A more reasonable definition of abstract data type would require a mathemati- cal ‘‘abstract’’ read more..

  • Page - 44

    Section 2.5.2 User-Defined Types 33 v vo oi id d f f(c co om mp pl le ex x z z) { c co om mp pl le ex x a a = 2 2.3 3; c co om mp pl le ex x b b = 1 1/a a; c co om mp pl le ex x c c = a a+b b*c co om mp pl le ex x(1 1,2 2.3 3) ; / / ... i if f ( c c != b b) c c = -( b b/a a)+2 2*b b; } The compiler converts read more..

  • Page - 45

    34 A Tour of C++ Chapter 2 The constructor initializes a new S St ta ac ck k variable. To do so, it allocates some memory on the free store (also called the heap or dynamic store) using the n ne ew w operator. The destructor cleans up by freeing that memory. This is all done without intervention by users of S St ta ac ck ks. The users simply create and use read more..

  • Page - 46

    Section 2.5.4 Abstract Types 35 stack from changes to its implementation, this last S St ta ac ck k is insufficient. Then, the solution is to decouple the interface from the representation and give up genuine local variables. First, we define the interface: c cl la as ss s S St ta ac ck k { p pu ub bl li ic c: c cl la as ss s U Un nd de er rf fl lo read more..

  • Page - 47

    36 A Tour of C++ Chapter 2 Since f f() doesn’t know about A Ar rr ra ay y _ _s st ta ac ck ks but only knows the S St ta ac ck k interface, it will work just as well for a different implementation of a S St ta ac ck k. For example: c cl la as ss s L Li is st t _ _s st ta ac ck k : p pu ub bl li ic c S St ta ac ck k { / / read more..

  • Page - 48

    Section 2.5.5 Virtual Functions 37 The functions in the v vt tb bl l 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. All the caller needs to know is the location of the v vt tb bl l in a S St ta ac ck k and the index used for each virtual function. This virtual call mechanism read more..

  • Page - 49

    38 A Tour of C++ Chapter 2 v vo oi id d S Sh ha ap pe e: : d dr ra aw w() { s sw wi it tc ch h ( k k) { c ca as se e c ci ir rc cl le e: / / draw a circle b br re ea ak k; c ca as se e t tr ri ia an ng gl le e: / / draw a triangle b br re ea ak k; c ca as se e s sq qu ua ar re e: / / draw a square b br re ea read more..

  • Page - 50

    Section 2.6.2 Class Hierarchies 39 As in the abstract type S St ta ac ck k in §2.5.4, the functions for which the calling interface can be defined – but where the implementation cannot be defined yet – are v vi ir rt tu ua al l. In particular, the functions d dr ra aw w() and r ro ot ta at te e() can be defined only for specific shapes, so they are declared v vi read more..

  • Page - 51

    40 A Tour of C++ Chapter 2 mutually supportive. For example, classes and modules contain functions, while modules contain classes and functions. The experienced designer applies a variety of paradigms as need dictates. 2.7 Generic Programming [tour.generic] Someone who wants a stack is unlikely always to want a stack of characters. A stack is a general concept, independent of the read more..

  • Page - 52

    Section 2.7.1 Containers 41 t te em mp pl la at te e<c cl la as ss s T T> T T S St ta ac ck k<T T>: : p po op p() { i if f ( t to op p == 0 0) t th hr ro ow w U Un nd de er rf fl lo ow w() ; t to op p = t to op p - 1 1; r re et tu ur rn n v v[t to op p] ; } Given these definitions, we can use stacks like read more..

  • Page - 53

    42 A Tour of C++ Chapter 2 iterator that refers one beyond the last element of the sequence. The physical representation of ‘‘the end’’ may be a sentinel element, but it doesn’t have to be. In fact, the point is that this notion of sequences covers a wide variety of representations, including lists and arrays. We need some standard notation for operations such as ‘‘access an read more..

  • Page - 54

    Section 2.8 Postscript 43 2.8 Postscript [tour.post] 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 read more..

  • Page - 55

    44 A Tour of C++ Chapter 2 The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved. read more..

  • Page - 56

    _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 3 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ A Tour of the Standard Library Why waste time learning read more..

  • Page - 57

    46 A Tour of the Standard Library Chapter 3 as defined by the standard and to keep the examples portable, except where specifically noted. Nat- urally, a programmer is encouraged to explore the more extensive facilities available on most sys- tems, but that is left to exercises. 3.2 Hello, world! [tour2.hello] The minimal C++ program is i in nt t m ma ai in n() { } It read more..

  • Page - 58

    Section 3.3 The Standard Library Namespace 47 s st td d: : s st tr ri in ng g s s = " F Fo ou ur r l le eg gs s G Go oo od d; t tw wo o l le eg gs s B Ba aa aa ad d!"; s st td d: : l li is st t<s st td d: : s st tr ri in ng g> s sl lo og ga an ns s; For simplicity, I will rarely use the s st td d: : read more..

  • Page - 59

    48 A Tour of the Standard Library Chapter 3 A character constant is a character enclosed in single quotes. Note that a character constant is out- put as a character rather than as a numerical value. For example, v vo oi id d k k() { c co ou ut t << ´ a a´; c co ou ut t << ´ b b´; c co ou ut t << ´ c c´; } will output a ab bc c. read more..

  • Page - 60

    Section 3.5 Strings 49 The two ways of adding to the end of a string are semantically equivalent, but I prefer the latter because it is more concise and likely to be more efficiently implemented. Naturally, s st tr ri in ng gs can be compared against each other and against string literals. For example: s st tr ri in ng g i in nc ca an nt ta at ti io on n; read more..

  • Page - 61

    50 A Tour of the Standard Library Chapter 3 3.6 Input [tour2.istream] The standard library offers i is st tr re ea am ms for input. Like o os st tr re ea am ms, i is st tr re ea am ms 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 read more..

  • Page - 62

    Section 3.6 Input 51 the switch-statement. The case constants must be distinct. If the value tested does not match any of them, the d de ef fa au ul lt t is chosen. The programmer need not provide a d de ef fa au ul lt t. Often, we want to read a sequence of characters. A convenient way of doing that is to read into a s st tr ri in ng g. For example: read more..

  • Page - 63

    52 A Tour of the Standard Library Chapter 3 3.7 Containers [tour2.stl] Much computing involves creating collections of various forms of objects 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 suit- able containers for a read more..

  • Page - 64

    Section 3.7.1 Vector 53 Should you make the mistake of using [] where you meant () when declaring a v ve ec ct to or r, your com- piler will almost certainly catch the mistake and issue an error message when you try to use the v ve ec ct to or r. A v ve ec ct to or r is a single object that can be assigned. For example: v vo oi id d f f(v ve ec read more..

  • Page - 65

    54 A Tour of the Standard Library Chapter 3 v vo oi id d p pr ri in nt t _ _e en nt tr ry y(i in nt t i i) / / simple use, exactly as for vector { c co ou ut t << p ph ho on ne e _ _b bo oo ok k[i i].n na am me e << ´ ´ << p ph ho on ne e _ _b bo oo ok k[i i].n nu um mb be er r << ´ \ \n n´; } An read more..

  • Page - 66

    Section 3.7.3 List 55 f fo or r ( L LI I i i = p ph ho on ne e _ _b bo oo ok k.b be eg gi in n() ; i i != p ph ho on ne e _ _b bo oo ok k.e en nd d() ; ++ i i) { E En nt tr ry y& e e = * i i; / / reference used as shorthand i if f ( s s == e e.n na am me e) c co ou ut t << e e.n na am me e << ´ ´ read more..

  • Page - 67

    56 A Tour of the Standard Library Chapter 3 opposite properties. A m ma ap p resembles a l li is st t of (key,value) pairs except that it is optimized for find- ing values based on keys. The standard library provides some of the most general and useful container types to allow the programmer to select a container that best serves the needs of an application: _ read more..

  • Page - 68

    Section 3.8 Algorithms 57 The standard algorithms are described in Chapter 18. They are expressed in terms of sequences of elements (§2.7.2). A sequence is represented by a pair of iterators specifying the first element and the one-beyond-the-last element. In the example, s so or rt t() sorts the sequence from v ve e.b be eg gi in n() to v ve e.e en nd d() – read more..

  • Page - 69

    58 A Tour of the Standard Library Chapter 3 v vo oi id d f f() { s st tr ri in ng g m m = " M Ma ar ry y h ha ad d a a l li it tt tl le e l la am mb b"; i in nt t a a _ _c co ou un nt t = c co ou un nt t(m m,´a a´) ; } The first call to f fi in nd d() finds the ´ a a´ in M Ma ar ry y. Thus, the read more..

  • Page - 70

    Section 3.8.1 Use of Iterators 59 v vo oi id d f f(l li is st t<c co om mp pl le ex x>& l lc c, v ve ec ct to or r<s st tr ri in ng g>& v vs s, s st tr ri in ng g s s) { i in nt t i i1 1 = c co ou un nt t(l lc c.b be eg gi in n() , l lc c.e en nd d() , c co om mp pl le ex x(1 1,3 3)) ; i in nt read more..

  • Page - 71

    60 A Tour of the Standard Library Chapter 3 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 read more..

  • Page - 72

    Section 3.8.3 Iterators and I/O 61 i is st tr re ea am m _ _i it te er ra at to or r to indicate the end of input. This is the default i is st tr re ea am m _ _i it te er ra at to or r: i is st tr re ea am m _ _i it te er ra at to or r<s st tr ri in ng g> e eo os s; We could now read H He el ll lo o, w wo or rl read more..

  • Page - 73

    62 A Tour of the Standard Library Chapter 3 v vo oi id d r re ec co or rd d(c co on ns st t s st tr ri in ng g& s s) { h hi is st to og gr ra am m[s s]++; / / record frequency of ‘‘s’’ } Once the input has been read, we would like to output the data we have gathered. The m ma ap p consists of a sequence of (string,int) pairs. read more..

  • Page - 74

    Section 3.8.4 Traversals and Predicates 63 v vo oi id d g g(c co on ns st t m ma ap p<s st tr ri in ng g,i in nt t>& m m) { i in nt t c c4 42 2 = c co ou un nt t _ _i if f(m m.b be eg gi in n() , m m.e en nd d() , g gt t _ _4 42 2) ; / / ... } A function, such as g gt t _ _4 42 2(), that is used to control the read more..

  • Page - 75

    64 A Tour of the Standard Library Chapter 3 3.8.6 Standard Library Algorithms [tour2.algolist] What is an algorithm? 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 read more..

  • Page - 76

    Section 3.9.1 Complex Numbers 65 / / standard exponentiation function from <complex>: t te em mp pl la at te e<c cl la as ss s C C> c co om mp pl le ex x<C C> p po ow w(c co on ns st t c co om mp pl le ex x<C C>&, i in nt t) ; v vo oi id d f f(c co om mp pl le ex x<f fl lo oa at t> f fl l, c co om read more..

  • Page - 77

    66 A Tour of the Standard Library Chapter 3 3.10 Standard Library Facilities [tour2.post] The facilities provided by the standard library can be classified like this: [1] Basic run-time language support (e.g., for allocation and run-time type information); see §16.1.3. [2] The C standard library (with very minor modifications to minimize violations of the type system); see §16.1.2. [3] read more..

  • Page - 78

    Part I 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 4 Types and Declarations 5 read more..

  • Page - 79

    68 Basic Facilities Part I The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved. read more..

  • Page - 80

    _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 4 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Types and Declarations Accept nothing short of perfection! – read more..

  • Page - 81

    70 Types and Declarations Chapter 4 would make the example meaningful. Because y y is declared to be an i in nt t, it can be assigned to, used in arithmetic expressions, etc. On the other hand, f f is declared to be a function that takes an i in nt t as its argument, so it can be called given a suitable argument. This chapter presents fundamental types (§4.1.1) read more..

  • Page - 82

    Section 4.1.1 Fundamental Types 71 variations for optimizations and special needs that are best ignored until such needs arise. They must be known, however, to read old C and C++ code. 4.2 Booleans [dcl.bool] A Boolean, b bo oo ol l, can have one of the two values t tr ru ue e or f fa al ls se e. A Boolean is used to express the results of logical operations. read more..

  • Page - 83

    72 Types and Declarations Chapter 4 Almost universally, a c ch ha ar r 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 (§C.3). Serious read more..

  • Page - 84

    Section 4.3.1 Character Literals 73 4.3.1 Character Literals [dcl.char.lit] A character literal, often called a character constant, is a character enclosed in single quotes, for example, ´ a a´ and ´ 0 0´. The type of a character literal is c ch ha ar r. Such character literals are really symbolic constants for the integer value of the characters in the character set of read more..

  • Page - 85

    74 Types and Declarations Chapter 4 The suffix U U can be used to write explicitly u un ns si ig gn ne ed d literals. Similarly, the suffix L L can be used to write explicitly l lo on ng g literals. For example, 3 3 is an i in nt t, 3U is an u un ns si ig gn ne ed d i in nt t, and 3 3L L is a l lo on ng g i in nt t. If no suffix read more..

  • Page - 86

    Section 4.6 Sizes 75 when a program is written than to try to untangle the mess afterwards. 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 read more..

  • Page - 87

    76 Types and Declarations Chapter 4 The c ch ha ar r 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 i in nt t type is supposed to be chosen to be the most suitable for holding and manipulating integers on a given computer; it read more..

  • Page - 88

    Section 4.8 Enumerations 77 defines three integer constants, called enumerators, and assigns values to them. By default, enu- merator values are assigned increasing from 0 0, so A AS SM M==0 0, A AU UT TO O==1 1, and B BR RE EA AK K==2 2. An enu- meration can be named. For example: e en nu um m k ke ey yw wo or rd d { A AS SM M, A AU UT TO O, B read more..

  • Page - 89

    78 Types and Declarations Chapter 4 The s si iz ze eo of f an enumeration is the s si iz ze eo of f some integral type that can hold its range and not larger than s si iz ze eo of f(i in nt t), unless an enumerator cannot be represented as an i in nt t or as an u un ns si ig gn ne ed d i in nt t. For example, s si iz ze eo of f(e e1 read more..

  • Page - 90

    Section 4.9 Declarations 79 d do ou ub bl le e s sq qr rt t(d do ou ub bl le e d d) { /* ... */ } i in nt t e er rr ro or r _ _n nu um mb be er r = 1 1; s st tr ru uc ct t U Us se er r { /* ... */ }; There must always be exactly one definition for each name in a C++ program (for the effects of # i in nc cl lu ud de e, read more..

  • Page - 91

    80 Types and Declarations Chapter 4 c ch ha ar r* k ki in ng gs s[] = { " A An nt ti ig go on nu us s", "S Se el le eu uc cu us s", "P Pt to ol le em my y" }; Here, the base type is c ch ha ar r, the declarator is * k ki in ng gs s[], and the initializer is ={...} . A specifier is an initial keyword, such as v vi read more..

  • Page - 92

    Section 4.9.3 Names 81 4.9.3 Names [dcl.name] 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 com- piler writer (in particular, read more..

  • Page - 93

    82 Types and Declarations Chapter 4 4.9.4 Scope [dcl.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. For a name declared in a function (often called a local name), that scope extends from its point of declaration to the end of the block in which its declaration occurs. A block is a section read more..

  • Page - 94

    Section 4.9.4 Scope 83 v vo oi id d f f3 3() { i in nt t x x = x x; / / perverse: initialize x with its own (uninitialized) value } This is not illegal, just silly. A good compiler will warn if a variable is used before it has been set (see also §5.9[9]). It is possible to use a single name to refer to two different objects in a block without using the read more..

  • Page - 95

    84 Types and Declarations Chapter 4 Note that an empty pair of parentheses () in a declaration always means ‘‘function’’ (§7.1). For example: i in nt t a a[] = { 1 1, 2 2 }; / / array initializer P Po oi in nt t z z(1 1,2 2) ; / / function-style initializer (initialization by constructor) i in nt t f f() ; / / function declaration 4.9.6 Objects and Lvalues read more..

  • Page - 96

    Section 4.9.7 Typedef 85 t ty yp pe ed de ef f l lo on ng g i in nt t3 32 2; For good and bad, t ty yp pe ed de ef fs are synonyms for other types rather than distinct types. Consequently, t ty yp pe ed de ef fs mix freely with the types for which they are synonyms. People who would like to have distinct types with identical semantics or identical read more..

  • Page - 97

    86 Types and Declarations Chapter 4 4. ( ∗1.5) Write a program that prints out the letters ´ a a´..´z z´ and the digits ´ 0 0´..´9 9´ and their integer values. Do the same for other printable characters. Do the same again but use hexa- decimal notation. 5. ( ∗2) What, on your system, are the largest and the smallest values of the following types: c ch ha read more..

  • Page - 98

    _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 5 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Pointers, Arrays, and Structures The sublime and the read more..

  • Page - 99

    88 Pointers, Arrays, and Structures Chapter 5 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: c ch ha ar r c c = ´ a a´; c ch ha ar r* p p = & c c; / / p holds the address of c c ch read more..

  • Page - 100

    Section 5.2 Arrays 89 The number of elements of the array, the array bound, must be a constant expression (§C.5). If you need variable bounds, use a v ve ec ct to or r (§3.7.1, §16.3). For example: v vo oi id d f f(i in nt t i i) { i in nt t v v1 1[i i] ; / / error: array size not a constant expression v ve ec ct to or r<i in nt t> v v2 read more..

  • Page - 101

    90 Pointers, Arrays, and Structures Chapter 5 5.2.2 String Literals [ptr.string.literal] A string literal is a character sequence enclosed within double quotes: " t th hi is s i is s a a s st tr ri in ng g" A string literal contains one more character than it appears to have; it is terminated by the null char- acter ´ \ \0 0´, with the value 0 0. For read more..

  • Page - 102

    Section 5.2.2 String Literals 91 v vo oi id d g g() { i if f ( p p == q q) c co ou ut t << " o on ne e!\ \n n"; / / 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 read more..

  • Page - 103

    92 Pointers, Arrays, and Structures Chapter 5 p p1 1 p p2 2 p p3 3 . . 1 1 . . 2 2 . . 3 3 . . 4 4 . . v v: Taking a pointer to the element one beyond the end of an array is guaranteed to work. This is important for many algorithms (§2.7.2, §18.3). However, since such a pointer does not in fact point to an element of the array, it may not be used for read more..

  • Page - 104

    Section 5.3.1 Navigating Arrays 93 is equivalent to a traversal using a pointer: v vo oi id d f fp p(c ch ha ar r v v[]) { f fo or r ( c ch ha ar r* p p = v v; * p p!=0 0; p p++) u us se e(*p p) ; } The prefix * operator dereferences a pointer so that * p p is the character pointed to by p p,and ++ increments the pointer so that it refers to read more..

  • Page - 105

    94 Pointers, Arrays, and Structures Chapter 5 i in nt t* p p1 1 = v v2 2+2 2; / / p1 = &v2[2] i in nt t* p p2 2 = v v2 2-2 2; / / *p2 undefined } Complicated pointer arithmetic is usually unnecessary and often 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 read more..

  • Page - 106

    Section 5.4 Constants 95 v vo oi id d g g(c co on ns st t X X* p p) { / / can’t modify *p here } v vo oi id d h h() { X X v va al l; / / val can be modified g g(&v va al l) ; / / ... } Depending on how smart it is, a compiler can take advantage of an object being a constant in sev- eral ways. For example, the initializer for a constant read more..

  • Page - 107

    96 Pointers, Arrays, and Structures Chapter 5 c ca as se e b b: / / ... } } Enumerators (§4.8) are often an alternative to c co on ns st ts in such cases. The way c co on ns st t can be used with class member functions is discussed in §10.2.6 and §10.2.7. Symbolic constants should be used systematically to avoid ‘‘magic numbers’’ in code. If a numeric constant, such as read more..

  • Page - 108

    Section 5.4.1 Pointers and Constants 97 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 c co on ns st t, the function is prohibited from modifying the object pointed to. For example: c ch ha ar r* s st tr rc cp py y(c ch ha read more..

  • Page - 109

    98 Pointers, Arrays, and Structures Chapter 5 v vo oi id d g g() { i in nt t i ii i = 0 0; i in nt t& r rr r = i ii i; r rr r++; / / ii is incremented to 1 i in nt t* p pp p = & r rr r; / / pp points to ii } This is legal, but r rr r++ does not increment the reference r rr r; rather, ++ is applied to an i in nt t that read more..

  • Page - 110

    Section 5.5 References 99 v vo oi id d i in nc cr re em me en nt t(i in nt t& a aa a) { a aa a++; } v vo oi id d f f() { i in nt t x x = 1 1; i in nc cr re em me en nt t(x x) ; / / x = 2 } The semantics of argument passing are defined to be those of initialization, so when called, i in nc cr re em me en nt t’s argument a read more..

  • Page - 111

    100 Pointers, Arrays, and Structures Chapter 5 f fo or r ( i in nt t i i = 0 0; i i < p pa ai ir rs s.s si iz ze e() ; i i++) i if f ( s s == p pa ai ir rs s[i i].n na am me e) r re et tu ur rn n p pa ai ir rs s[i i].v va al l; P Pa ai ir r p p = { s s, 0 0 }; p pa ai ir rs s.p pu us sh h _ _b ba ac ck read more..

  • Page - 112

    Section 5.6 Pointer to Void 101 i in nt t* p pi i2 2 = s st ta at ti ic c _ _c ca as st t<i in nt t*>(p pv v) ; / / explicit conversion back to int* d do ou ub bl le e* p pd d1 1 = p pv v; / / error d do ou ub bl le e* p pd d2 2 = p pi i; / / error d do ou ub bl le e* p pd d3 3 = s st ta at ti ic c _ _c ca read more..

  • Page - 113

    102 Pointers, Arrays, and Structures Chapter 5 v vo oi id d f f() { a ad dd dr re es ss s j jd d; j jd d.n na am me e = " J Ji im m D Da an nd dy y"; j jd d.n nu um mb be er r = 6 61 1; } The notation used for initializing arrays can also be used for initializing variables of structure types. For example: a ad dd dr re es ss s j read more..

  • Page - 114

    Section 5.7 Structures 103 s si iz ze eo of f(a ad dd dr re es ss s) is 2 24 4, and not 2 22 2 as might be expected. You can minimize wasted space by sim- ply ordering members by size (largest member first). However, it is usually best to order members for readability and sort them by size only if there is a demonstrated need to optimize. The name of a read more..

  • Page - 115

    104 Pointers, Arrays, and Structures Chapter 5 f f() ; / / error: S not defined; size needed to return value g g(a a) ; / / error: S not defined; size needed to pass argument p p->m m = 7 7; / / error: S not defined; member name not known S S* q q = h h(p p) ; / / ok: pointers can be allocated and passed q q->m m = 7 7; / / error: S not read more..

  • Page - 116

    Section 5.9 Exercises 105 5.9 Exercises [ptr.exercises] 1. ( ∗1) Write declarations for the following: a pointer to a character, an array of 10 integers, a ref- erence to an array of 10 integers, a pointer to an array of character strings, a pointer to a pointer to a character, a constant integer, a pointer to a constant integer, and a constant pointer to an integer. read more..

  • Page - 117

    106 Pointers, Arrays, and Structures Chapter 5 . The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved. read more..

  • Page - 118

    _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 6 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Expressions and Statements Premature optimization is the root read more..

  • Page - 119

    108 Expressions and Statements Chapter 6 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 read more..

  • Page - 120

    Section 6.1.1 The Parser 109 e en nu um m T To ok ke en n _ _v va al lu ue e { N NA AM ME E, N NU UM MB BE ER R, E EN ND D, P PL LU US S=´+´, M MI IN NU US S=´-´, M MU UL L=´*´, D DI IV V=´/´, P PR RI IN NT T=´;´, A AS SS SI IG GN N=´=´, L LP P=´(´, R RP P=´)´ }; T To ok ke en n _ _v va al lu ue e c cu ur read more..

  • Page - 121

    110 Expressions and Statements Chapter 6 l le ef ft t=l le ef ft t-t te er rm m() could have been used without changing the meaning of the program. However, l le ef ft t+=t te er rm m() and l le ef ft t-=t te er rm m() not only are shorter but also express the intended operation directly. Each assignment operator is a separate lexical token, so a a + = read more..

  • Page - 122

    Section 6.1.1 The Parser 111 and the resulting value is the value of the condition (§6.3.2.1). Consequently, the division and assignment l le ef ft t/=d d is done if and only if d d is nonzero. The function p pr ri im m() handling a primary is much like e ex xp pr r() and t te er rm m(), except that because we are getting lower in the call hierarchy a read more..

  • Page - 123

    112 Expressions and Statements Chapter 6 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 m ma ap p (§3.7.4, §17.4.1): m ma ap p<s st tr ri in ng g,d do ou ub bl le e> t ta ab bl le e; That is, when t ta ab bl le e is indexed by a read more..

  • Page - 124

    Section 6.1.2 The Input Function 113 Let us look at some of the cases separately before considering the complete function. The expression terminator ´;´ , the parentheses, and the operators are handled simply by returning their values: c ca as se e ´;´: c ca as se e ´*´: c ca as se e ´/´: c ca as se e ´+´: c ca as se e ´-´: c ca as se e ´(´: c ca read more..

  • Page - 125

    114 Expressions and Statements Chapter 6 s sw wi it tc ch h ( c ch h) { c ca as se e 0 0: r re et tu ur rn n c cu ur rr r _ _t to ok k=E EN ND D; c ca as se e ´;´: c ca as se e ´*´: c ca as se e ´/´: c ca as se e ´+´: c ca as se e ´-´: c ca as se e ´(´: c ca as se e ´)´: c ca as se e ´=´: r re et tu ur read more..

  • Page - 126

    Section 6.1.3 Low-level Input 115 s sw wi it tc ch h ( c ch h) { c ca as se e ´;´: c ca as se e ´ \ \n n´: r re et tu ur rn n c cu ur rr r _ _t to ok k=P PR RI IN NT T; A do-statement is used; it is equivalent to a while-statement except that the controlled statement is always executed at least once. The call c ci in n.g ge et t(c ch read more..

  • Page - 127

    116 Expressions and Statements Chapter 6 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 g ge et t _ _t to ok ke en n() kept track of read more..

  • Page - 128

    Section 6.1.5 The Driver 117 w wh hi il le e ( c ci in n) { / / ... i if f ( c cu ur rr r _ _t to ok k == P PR RI IN NT T) c co on nt ti in nu ue e; c co ou ut t << e ex xp pr r(f fa al ls se e) << ´ \ \n n´; } is equivalent to w wh hi il le e ( c ci in n) { / / ... i if f ( c cu ur rr r _ _t to ok k read more..

  • Page - 129

    118 Expressions and Statements Chapter 6 2 a ar rg gc c: a ar rg gv v: 0 0 . . "d dc c" "1 15 50 0/ /1 1. .1 19 93 34 4" Because the conventions for calling m ma ai in n() are shared with C, C-style arrays and strings are used. It is not difficult to get hold of a command-line argument. The problem is how to use it with minimal read more..

  • Page - 130

    Section 6.1.7 Command-Line Arguments 119 An i is st tr ri in ng gs st tr re ea am m is a kind of i is st tr re ea am m that reads from its character string argument (§21.5.3). Upon reaching the end of its string, an i is st tr ri in ng gs st tr re ea am m fails exactly like other streams do when they hit the end of input (§3.6, §21.3.3). To read more..

  • Page - 131

    120 Expressions and Statements Chapter 6 _ ____________________________________________________________ Operator Summary _ ____________________________________________________________ _ ____________________________________________________________ scope resolution class _name :: member scope resolution namespace _name :: member global :: name global :: qualified-name _ ____________________________________________________________ member selection read more..

  • Page - 132

    Section 6.2 Operator Summary 121 _ _______________________________________ Operator Summary (continued) _ _______________________________________ _ _______________________________________ add (plus) expr + expr subtract (minus) expr - expr _ _______________________________________ shift left expr << expr shift right expr >> expr _ _______________________________________ less than expr < expr less than or equal read more..

  • Page - 133

    122 Expressions and Statements Chapter 6 6.2.1 Results [expr.res] The result types of arithmetic operators are determined by a set of rules known as ‘‘the usual arith- metic conversions’’ (§C.6.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 floating-point read more..

  • Page - 134

    Section 6.2.2 Evaluation Order 123 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, i in nt t i i = 1 1; v v[i i] = i i++; / / undefined result may be evaluated as either v v[1 1]=1 1 or v v[2 2]=1 1 or may cause some read more..

  • Page - 135

    124 Expressions and Statements Chapter 6 This does not apply a mask to i i and then test if the result is zero. Because == has higher prece- dence than & , the expression is interpreted as i i&(m ma as sk k==0 0). Fortunately, it is easy enough for a compiler to warn about most such mistakes. In this case, parentheses are important: i if f (( i i&m ma read more..

  • Page - 136

    Section 6.2.4 Bitwise Logical Operators 125 i in nt t d di if ff f = c ci in n.r rd ds st ta at te e()^c co ou ut t.r rd ds st ta at te e() ; / / rdstate() returns the state Computing differences of stream states is not very common. For other similar types, computing differences is essential. For example, consider comparing a bit vector that represents the read more..

  • Page - 137

    126 Expressions and Statements Chapter 6 i in nt t l le en ng gt th h = s st tr rl le en n(q q) ; f fo or r ( i in nt t i i = 0 0; i i<=l le en ng gt th h; i i++) p p[i i] = q q[i 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 read more..

  • Page - 138

    Section 6.2.5 Increment and Decrement 127 instructions. Therefore, you should measure carefully before believing that some piece of hand- crafted code outperforms library functions. 6.2.6 Free Store [expr.free] A named object has its lifetime determined by its scope (§4.9.4). However, it is often useful to cre- ate an object that exists independently of the scope in which it was read more..

  • Page - 139

    128 Expressions and Statements Chapter 6 An object created by n ne ew w exists until it is explicitly destroyed by d de el le et te e. Then, the space it occu- pied can be reused by n ne ew w. A C++ implementation does not guarantee the presence of a ‘‘garbage collector’’ that looks out for unreferenced objects and makes them available to n ne ew w for read more..

  • Page - 140

    Section 6.2.6.2 Memory Exhaustion 129 6.2.6.2 Memory Exhaustion [expr.exhaust] The free store operators n ne ew w, d de el le et te e, n ne ew w[], and d de el le et te e[] are implemented using functions: v vo oi id d* o op pe er ra at to or r n ne ew w(s si iz ze e _ _t t) ; / / space for individual object v vo oi id d o op pe er ra at read more..

  • Page - 141

    130 Expressions and Statements Chapter 6 because you provided your own o op pe er ra at to or r n ne ew w() and o op pe er ra at to or r d de el le et te e() – the handler might attempt to find some memory for n ne ew w to return. In other words, a user might provide a garbage collector, thus rendering the use of d de el le et te e read more..

  • Page - 142

    Section 6.2.7 Explicit Type Conversion 131 A form of run-time checked conversion, d dy yn na am mi ic c _ _c ca as st t (§15.4.1), and a cast for removing c co on ns st t qualifiers, c co on ns st t _ _c ca as st t (§15.4.2.1), are also provided. From C, C++ inherited the notation ( T T)e e, which performs any conversion that can be expressed as a combination of s read more..

  • Page - 143

    132 Expressions and Statements Chapter 6 6.3 Statement Summary [expr.stmts] Here are a summary and some examples of C++ statements: _ ______________________________________________________________ Statement Syntax _ ______________________________________________________________ _ ______________________________________________________________ statement: declaration { statement-list opt } t tr ry y { statement-list opt } read more..

  • Page - 144

    Section 6.3.1 Declarations as Statements 133 6.3.1 Declarations as Statements [expr.dcl] A declaration is a statement. Unless a variable is declared s st ta at ti ic c, its initializer is executed when- ever the thread of control passes through the declaration (see also §10.4.8). The reason for allow- ing declarations wherever a statement can be used (and a few other places; read more..

  • Page - 145

    134 Expressions and Statements Chapter 6 means i if f ( x x != 0 0) / / ... For a pointer p p, i if f ( p p) / / ... is a direct statement of the test ‘‘does p p point to a valid object,’’ whereas i if f ( p p != 0 0) / / ... states the same question indirectly by comparing to a value known not to point to an object. Note that the representation read more..

  • Page - 146

    Section 6.3.2 Selection Statements 135 i if f ( v va al l == 1 1) f f() ; e el ls se e i if f ( v va al l == 2 2) g g() ; e el ls se e h h() ; The meaning is the same, but the first (s sw wi it tc ch h) version is preferred because the nature of the opera- tion (testing a value against a set of constants) is explicit. This makes the s sw read more..

  • Page - 147

    136 Expressions and Statements Chapter 6 The obvious and traditional alternative is to declare d d before the condition. However, this opens the scope (literally) for the use of d d before its initialization or after its intended useful life: d do ou ub bl le e d d; / / ... d d2 2 = d d; / / oops! / / ... i if f ( d d = p pr ri im m(t tr ru ue e)) { read more..

  • Page - 148

    Section 6.3.3 Iteration Statements 137 w wh hi il le e(c ci in n>>c ch h) / / ... 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. read more..

  • Page - 149

    138 Expressions and Statements Chapter 6 f fo or r ( i i = 0 0; i i<n n; i i++) f fo or r ( j j = 0 0; j j<m m; j j++) i if f ( n nm m[i i][j j] == a a) g go ot to o f fo ou un nd d; / / not found / / ... f fo ou un nd d: / / nm[i][j] == a } There is also a c co on nt ti in nu ue e statement that, in effect, goes to read more..

  • Page - 150

    Section 6.4 Comments and Indentation 139 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. My preference is for: [1] A comment for each source file stating what the declarations in it have in common, refer- ences to manuals, general read more..

  • Page - 151

    140 Expressions and Statements Chapter 6 [11] Keep comments crisp; §6.4. [12] Maintain a consistent indentation style; §6.4. [13] Prefer defining a member o op pe er ra at to or r n ne ew w() (§15.6) to replacing the global o op pe er ra at to or r n ne ew w(); §6.2.6.2. [14] When reading input, always consider ill-formed input; §6.1.3. 6.6 Exercises [expr.exercises] 1. read more..

  • Page - 152

    Section 6.6 Exercises 141 * p p++ *-- p p ++ a a-- ( i in nt t*)p p->m m * p p.m m * a a[i i] 10. (*2) Write these functions: s st tr rl le en n(), which returns the length of a C-style string; s st tr rc cp py y(), which copies a string into another; and s st tr rc cm mp p(), which compares two strings. Consider what the argument types and return read more..

  • Page - 153

    142 Expressions and Statements Chapter 6 character constant notation. 17. ( ∗2) Write a function i it to oa a(i in nt t i i, c ch ha ar r b b[]) that creates a string representation of i i in b b and returns b b. 18. (*2) Type in the calculator example and get it to work. Do not ‘‘save time’’ by using an already entered text. You’ll learn most from read more..

  • Page - 154

    _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 7 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Functions To iterate is human, to recurse divine. – L. read more..

  • Page - 155

    144 Functions Chapter 7 A function declaration may contain argument names. This can be a help to the reader of a pro- gram, but the compiler simply ignores such names. As mentioned in §4.7, v vo oi id d as a return type means that the function does not return a value. 7.1.1 Function Definitions [fct.def] Every function that is called in a program must be defined read more..

  • Page - 156

    Section 7.1.2 Static Variables 145 7.1.2 Static Variables [fct.static] A local variable is initialized when the thread of execution reaches its definition. By default, this happens in every call of the function and each invocation of the function has its own copy of the variable. If a local variable is declared s st ta at ti ic c, a single, statically allocated object will read more..

  • Page - 157

    146 Functions Chapter 7 v vo oi id d g g() { i in nt t i i = 1 1; i in nt t j j = 1 1; f f(i i,j j) ; } will increment j j but not i i. The first argument, i i, is passed by value, the second argument, j j, is passed by reference. As mentioned in §5.5, functions that modify call-by-reference arguments can make programs hard to read and should most often be read more..

  • Page - 158

    Section 7.2 Argument Passing 147 v vo oi id d u up pd da at te e(f fl lo oa at t& i i) ; v vo oi id d g g(d do ou ub bl le e d d, f fl lo oa at t r r) { u up pd da at te e(2 2.0 0f f) ; / / error: const argument u up pd da at te e(r r) ; / / pass ref to r u up pd da at te e(d d) ; / / error: type conversion read more..

  • Page - 159

    148 Functions Chapter 7 7.3 Value Return [fct.return] A value must be returned from a function that is not declared v vo oi id d (however, m ma ai in n() is special; see §3.2). Conversely, a value cannot be returned from a v vo oi id d function. For example: i in nt t f f1 1() { } / / error: no value returned v vo oi id d f f2 2() { } / / ok i read more..

  • Page - 160

    Section 7.4 Overloaded Function Names 149 7.4 Overloaded Function Names [fct.over] Most often, it is a good idea to give different functions different names, but when some functions conceptually perform the same task on objects of different types, it can be more convenient to give them the same name. Using the same name for operations on different types is called overloading. The read more..

  • Page - 161

    150 Functions Chapter 7 v vo oi id d p pr ri in nt t(i in nt t) ; v vo oi id d p pr ri in nt t(c co on ns st t c ch ha ar r*) ; v vo oi id d p pr ri in nt t(d do ou ub bl le e) ; v vo oi id d p pr ri in nt t(l lo on ng g) ; v vo oi id d p pr ri in nt t(c ch ha ar r) ; v vo oi id d h h(c ch ha ar r c read more..

  • Page - 162

    Section 7.4 Overloaded Function Names 151 errors. In the previous example, this implies that only one of the four calls with a ‘‘wrong’’ argu- ment is caught by the compiler. Thus, overloading can increase the chances that an unsuitable argument will be rejected by the compiler. 7.4.1 Overloading and Return Type [fct.return] Return types are not considered in overload read more..

  • Page - 163

    152 Functions Chapter 7 v vo oi id d k k(i in nt t i i) { f f1 1(i i) ; / / ambiguous: f1(char) or f1(long) f f2 2(0 0) ; / / ambiguous: f2(char*) or f2(int*) } Where possible, the thing to do in such cases is to consider the set of overloaded versions of a func- tion as a whole and see if it makes sense according to the semantics of the function. read more..

  • Page - 164

    Section 7.4.4 Resolution for Multiple Arguments 153 v vo oi id d g g() { d do ou ub bl le e d d = p po ow w(2 2.0 0,2 2) ; / / error: pow(int(2.0),2) or pow(2.0,double(2))? } The call is ambiguous because 2 2.0 0 is the best match for the first argument of p po ow w(d do ou ub bl le e,d do ou ub bl le e) and 2 2 is the best match for the read more..

  • Page - 165

    154 Functions Chapter 7 v vo oi id d f f(i in nt t x x = 7 7) ; v vo oi id d f f(i in nt t = 7 7) ; / / ok v vo oi id d f f(i in nt t = 8 8) ; / / error: different default arguments v vo oi id d g g() { v vo oi id d f f(i in nt t x x = 9 9) ; / / ok: this declaration hides the outer one / / ... } Declaring a name in a read more..

  • Page - 166

    Section 7.6 Unspecified Number of Arguments 155 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 type of arguments vary is the ellipsis necessary. The most common use of the ellipsis is to specify an interface to C library func- tions that were defined before C++ read more..

  • Page - 167

    156 Functions Chapter 7 f fo or r (;;) { c ch ha ar r* p p = v va a _ _a ar rg g(a ap p,c ch ha ar r*) ; i if f ( p p == 0 0) b br re ea ak k; c ce er rr r << p p << ´ ´; } v va a _ _e en nd d(a ap p) ; / / arg cleanup c ce er rr r << ´ \ \n n´; i if f ( s se ev ve er ri it ty y) e ex xi it t(s read more..

  • Page - 168

    Section 7.7 Pointer to Function 157 v vo oi id d (* p pf f)(s st tr ri in ng g) ; / / pointer to void(string) v vo oi id d f f1 1(s st tr ri in ng g) ; / / void(string) i in nt t f f2 2(s st tr ri in ng g) ; / / int(string) v vo oi id d f f3 3(i in nt t*) ; / / void(int*) v vo oi id d f f() { p pf f = & f f1 1; / / ok read more..

  • Page - 169

    158 Functions Chapter 7 One way to gain appreciation of the expressive power of pointers to functions is to try to write such code without them – and without using their better-behaved cousins, the virtual functions (§12.2.6). A menu can be modified at run-time by inserting new functions into the operator table. It is also easy to construct new menus at run-time. Pointers read more..

  • Page - 170

    Section 7.7 Pointer to Function 159 U Us se er r h he ea ad ds s[] = { " R Ri it tc ch hi ie e D D.M M", "d dm mr r", 1 11 12 27 71 1, " S Se et th hi i R R.", "r ra av vi i", 1 11 12 27 72 2, " S Sz zy ym ma an ns sk ki i T T.G G.", "t tg gs s", 1 11 12 27 73 3, " S Sc ch read more..

  • Page - 171

    160 Functions Chapter 7 A function must be called through a pointer to function with exactly the right argument and return types. There is no implicit conversion of argument or return types when pointers to functions are assigned or initialized. This means that i in nt t c cm mp p3 3(c co on ns st t m my yt ty yp pe e*,c co on ns st t m my yt ty yp pe read more..

  • Page - 172

    Section 7.8 Macros 161 Macros manipulate character strings and know little about C++ syntax and nothing about C++ types or scope rules. Only the expanded form of a macro is seen by the compiler, so an error in a macro will be reported when the macro is expanded, not when it is defined. This leads to very obscure error messages. Here are some plausible macros: # d de read more..

  • Page - 173

    162 Functions Chapter 7 When writing a macro, it is not unusual to need a new name for something. A string can be created by concatenating two strings using the ## macro operator. For example, # d de ef fi in ne e N NA AM ME E2 2(a a,b b) a a##b b i in nt t N NA AM ME E2 2(h ha ac ck k,c ca ah h)() ; will produce i in nt t h ha ac ck kc ca read more..

  • Page - 174

    Section 7.9 Advice 163 7.9 Advice [dcl.advice] [1] Be suspicious of non-c co on ns st t reference arguments; if you want the function to modify its argu- ments, use pointers and value return instead; §5.5. [2] Use c co on ns st t reference arguments when you need to minimize copying of arguments; §5.5. [3] Use c co on ns st t extensively and consistently; §7.2. [4] read more..

  • Page - 175

    164 Functions Chapter 7 Write a function for entering new words into a tree of T Tn no od de es. Write a function to write out a tree of T Tn no od de es. Write a function to write out a tree of T Tn no od de es with the words in alphabetical order. Modify T Tn no od de e so that it stores (only) a pointer to an arbitrarily long word stored as read more..

  • Page - 176

    _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 8 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Namespaces and Exceptions The year is 787! A.D.? – Monty read more..

  • Page - 177

    166 Namespaces and Exceptions Chapter 8 driver parser lexer symbol table error handler where an arrow means ‘‘using.’’ To simplify the picture, I have not represented the fact that every part relies on error handling. In fact, the calculator was conceived as three parts, with the driver and error handler added for completeness. When one module uses another, it doesn’t need read more..

  • Page - 178

    Section 8.1 Modularization and Interfaces 167 the calculator in stages. In ‘‘real life,’’ a program is unlikely to grow through all of these stages. An experienced programmer might pick a design that is ‘‘about right’’ from the start. However, as a program evolves over the years, dramatic structural changes are not uncommon. Error handling permeates the structure of a program. read more..

  • Page - 179

    168 Namespaces and Exceptions Chapter 8 This use of namespaces makes it reasonably obvious what the lexer and the parser provide to a user. However, had I included the source code for the functions, this structure would have been obscured. If function bodies are included in the declaration of a realistically-sized namespace, you typically have to wade through pages or screenfuls read more..

  • Page - 180

    Section 8.2 Namespaces 169 indicate its logical role in the program. The exception is m ma ai in n(), which must be global in order for the run-time environment to recognize it as special (§8.3.3). 8.2.1 Qualified Names [name.qualified] A namespace is a scope. The usual scope rules hold for namespaces, so if a name is previously declared in the namespace or in an enclosing read more..

  • Page - 181

    170 Namespaces and Exceptions Chapter 8 c ca as se e L Le ex xe er r: : L LP P: { d do ou ub bl le e e e = e ex xp pr r(t tr ru ue e) ; i if f ( L Le ex xe er r: : c cu ur rr r _ _t to ok k != L Le ex xe er r: : R RP P) r re et tu ur rn n E Er rr ro or r: : e er rr ro or r(") e ex xp pe ec ct te ed read more..

  • Page - 182

    Section 8.2.2 Using Declarations 171 However, all parser functions use similar sets of names from other modules. We can therefore place the using-declarations in the P Pa ar rs se er r’s namespace definition: n na am me es sp pa ac ce e P Pa ar rs se er r { d do ou ub bl le e p pr ri im m(b bo oo ol l) ; d do ou ub bl le e t te er rm m(b read more..

  • Page - 183

    172 Namespaces and Exceptions Chapter 8 u us si in ng g n na am me es sp pa ac ce e L Le ex xe er r; / / make all names from Lexer available u us si in ng g n na am me es sp pa ac ce e E Er rr ro or r; / / make all names from Error available } This allows us to write P Pa ar rs se er r’s functions exactly as we originally did read more..

  • Page - 184

    Section 8.2.4 Multiple Interfaces 173 n na am me es sp pa ac ce e P Pa ar rs se er r { / / interface for implementers d do ou ub bl le e p pr ri im m(b bo oo ol l) ; d do ou ub bl le e t te er rm m(b bo oo ol l) ; d do ou ub bl le e e ex xp pr r(b bo oo ol l) ; u us si in ng g L Le ex xe er r: : g ge et t _ _t read more..

  • Page - 185

    174 Namespaces and Exceptions Chapter 8 When dependencies are considered, it is important to remember that compilers and program- mers tend to take a somewhat simple-minded approach to them: ‘‘If a definition is in scope at point X, then anything written at point X depends on anything stated in that definition.’’ Typically, things are not really that bad because most read more..

  • Page - 186

    Section 8.2.4.1 Interface Design Alternatives 175 Now the d dr ri iv ve er r appears vulnerable to any change in the P Pa ar rs se er r interface from which it was sup- posed to be insulated. Even this appearance of a dependency is undesirable, so we explicitly restrict P Pa ar rs se er r _ _i in nt te er rf fa ac ce e’s dependency on P Pa ar rs se read more..

  • Page - 187

    176 Namespaces and Exceptions Chapter 8 P Pa ar rs se er r _ _i in nt te er rf fa ac ce e P Pa ar rs se er r . . D Dr ri iv ve er r . . P Pa ar rs se er r implementation P Pa ar rs se er r _ _i in nt te er rf fa ac ce e implementation Now all dependencies are minimized. Everything is concrete and properly named. However, for most problems I read more..

  • Page - 188

    Section 8.2.5.1 Unnamed Namespaces 177 8.2.5.1 Unnamed Namespaces [name.unnamed] It is often useful to wrap a set of declarations in a namespace simply to protect against the possibil- ity of name clashes. That is, the aim is to preserve locality of code rather than to present an inter- face to users. For example: # i in nc cl lu ud de e " h he ea ad de er r.h read more..

  • Page - 189

    178 Namespaces and Exceptions Chapter 8 s st td d: : s st tr ri in ng g f fo or rm ma at t(c co on ns st t D Da at te e&) ; / / make string representation / / ... } v vo oi id d f f(C Ch hr ro on no o: : D Da at te e d d, i in nt t i i) { s st td d: : s st tr ri in ng g s s = f fo or rm ma at t(d d) ; / / read more..

  • Page - 190

    Section 8.2.7 Namespace Aliases 179 n na am me es sp pa ac ce e A Am me er ri ic ca an n _ _T Te el le ep ph ho on ne e _ _a an nd d _ _T Te el le eg gr ra ap ph h { / / too long / / ... } A Am me er ri ic ca an n _ _T Te el le ep ph ho on ne e _ _a an nd d _ _T Te el le eg gr ra ap ph h: : S St tr ri in ng read more..

  • Page - 191

    180 Namespaces and Exceptions Chapter 8 Given this, we can now write the program in terms of M My y _ _l li ib b: v vo oi id d f f() { M My y _ _l li ib b: : S St tr ri in ng g s s = " B By yr ro on n"; / / finds My _lib::His_string::String / / ... } u us si in ng g n na am me es sp pa ac ce e M My y _ _l li ib b; v vo read more..

  • Page - 192

    Section 8.2.8.1 Selection 181 n na am me es sp pa ac ce e H Hi is s _ _s st tr ri in ng g { / / part of His _string only c cl la as ss s S St tr ri in ng g { /* ... */ }; S St tr ri in ng g o op pe er ra at to or r+(c co on ns st t S St tr ri in ng g&, c co on ns st t S St tr ri in ng g&) ; S St tr ri read more..

  • Page - 193

    182 Namespaces and Exceptions Chapter 8 When looking into a namespace, names explicitly declared there (including names declared by using-declarations) take priority over names made accessible in another scope by a using-directive (see also §C.10.1). Consequently, a user of M My y _ _l li ib b will see the name clashes for S St tr ri in ng g and V Ve ec ct to or r read more..

  • Page - 194

    Section 8.2.9.1 Namespaces and C 183 The using-directive is the key to achieving this. For example, the declarations of the standard C I/O facilities from the C header s st td di io o.h h are wrapped in a namespace like this: / / stdio.h: n na am me es sp pa ac ce e s st td d { / / ... i in nt t p pr ri in nt tf f(c co on ns st t c ch ha ar read more..

  • Page - 195

    184 Namespaces and Exceptions Chapter 8 v vo oi id d g g() { f f(´a a´) ; / / calls the f() from B.h } This program can be upgraded to a version using namespaces without changing the actual code: / / new A.h: n na am me es sp pa ac ce e A A { v vo oi id d f f(i in nt t) ; / / ... } / / new B.h: n na am me es sp pa ac ce e B B { v read more..

  • Page - 196

    Section 8.2.9.3 Namespaces Are Open 185 of users by presenting different parts of a namespace. This openness is also an aid to transition. For example, / / my header: v vo oi id d f f() ; / / my function / / ... # i in nc cl lu ud de e<s st td di io o.h h> i in nt t g g() ; / / my function / / ... can be rewritten without reordering of the read more..

  • Page - 197

    186 Namespaces and Exceptions Chapter 8 8.3 Exceptions [name.except] When a program is composed of separate modules, and especially when those modules come from separately developed libraries, error handling needs to be separated into two distinct parts: [1] The reporting of error conditions that cannot be resolved locally [2] The handling of errors detected elsewhere The author of a read more..

  • Page - 198

    Section 8.3.1 Throw and Catch 187 c ch ha ar r t to o _ _c ch ha ar r(i in nt t i i) { i if f ( i i<n nu um me er ri ic c _ _l li im mi it ts s<c ch ha ar r>: : m mi in n() || n nu um me er ri ic c _ _l li im mi it ts s<c ch ha ar r>: : m ma ax x()<i i)/ / see §22.2 t th hr ro ow w R Ra an ng ge e read more..

  • Page - 199

    188 Namespaces and Exceptions Chapter 8 examined. If the exception thrown is of a type specified for a handler, that handler is executed. If not, the exception handlers are ignored and the try-block acts just like an ordinary block. Basically, C++ exception handling is a way to transfer control to designated code in a calling function. Where needed, some information about the read more..

  • Page - 200

    Section 8.3.2 Discrimination of Exceptions 189 c ca at tc ch h ( Z Ze er ro o _ _d di iv vi id de e) { / / handle divide by zero } / / we get here if expr didn’t cause an exception or if a Syntax _error / / or Zero _divide exception was caught (and its handler didn’t return, / / throw an exception, or in some other way alter the flow of control). A read more..

  • Page - 201

    190 Namespaces and Exceptions Chapter 8 However, such nesting is rare in human-written code and is more often than not an indication of poor style. 8.3.3 Exceptions in the Calculator [name.calc] Given the basic exception-handling mechanism, we can rework the calculator example from §6.1 to separate the handling of errors found at run-time from the main logic of the calculator. This read more..

  • Page - 202

    Section 8.3.3 Exceptions in the Calculator 191 c ca as se e L Le ex xe er r: : E EN ND D: r re et tu ur rn n 1 1; d de ef fa au ul lt t: t th hr ro ow w E Er rr ro or r: : S Sy yn nt ta ax x _ _e er rr ro or r("p pr ri im ma ar ry y e ex xp pe ec ct te ed d") ; } } When a syntax error is detected, t th hr ro read more..

  • Page - 203

    192 Namespaces and Exceptions Chapter 8 The function s sk ki ip p() tries to bring the parser into a well-defined state after an error by skipping tokens until it finds an end-of-line or a semicolon. It, n no o _ _o of f _ _e er rr ro or rs s,and i in np pu ut t are obvious candi- dates for a D Dr ri iv ve er r namespace: n na am me es sp pa ac read more..

  • Page - 204

    Section 8.3.3.1 Alternative Error-Handling Strategies 193 w wh hi il le e (* D Dr ri iv ve er r: : i in np pu ut t) { t tr ry y { L Le ex xe er r: : g ge et t _ _t to ok ke en n() ; i if f ( L Le ex xe er r: : c cu ur rr r _ _t to ok k == L Le ex xe er r: : E EN ND D) b br re ea ak k; i if f ( L Le ex xe er r: read more..

  • Page - 205

    194 Namespaces and Exceptions Chapter 8 c ca as se e 2 2: / / read argument string i in np pu ut t = n ne ew w i is st tr ri in ng gs st tr re ea am m(a ar rg gv v[1 1]) ; b br re ea ak k; d de ef fa au ul lt t: c ce er rr r << " t to oo o m ma an ny y a ar rg gu um me en nt ts s\ \n n"; r re et tu ur read more..

  • Page - 206

    Section 8.5 Exercises 195 6. ( ∗2) Modify the program from §8.5[5] to measure if there is a difference in the cost of catching exceptions depending on where in a class stack the exception is thrown. Add a string object to each function and measure again. 7. ( ∗1) Find the error in the first version of m ma ai in n() in §8.3.3.1. 8. ( ∗2) Write a function that either returns read more..

  • Page - 207

    196 Namespaces and Exceptions Chapter 8 The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved. read more..

  • Page - 208

    _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 9 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Source Files and Programs Form must follow function. – Le read more..

  • Page - 209

    198 Source Files and Programs Chapter 9 only where necessary to distinguish what the programmer sees from what the compiler considers. To enable separate compilation, the programmer must supply declarations providing the type information needed to analyze a translation unit in isolation from the rest of the program. The declarations in a program consisting of many separately compiled read more..

  • Page - 210

    Section 9.2 Linkage 199 / / file2.c: i in nt t x x; / / meaning int x = 0; e ex xt te er rn n d do ou ub bl le e b b; e ex xt te er rn n i in nt t c c; There are three errors here: x x is defined twice, b b is declared twice with different types, and c c is declared twice but not defined. These kinds of errors (linkage errors) cannot be read more..

  • Page - 211

    200 Source Files and Programs Chapter 9 / / file1.c: t ty yp pe ed de ef f i in nt t T T; c co on ns st t i in nt t x x = 7 7; / / file2.c: t ty yp pe ed de ef f v vo oi id d T T; c co on ns st t i in nt t x x = 8 8; Global variables that are local to a single compilation unit are a common source of confusion and are best read more..

  • Page - 212

    Section 9.2.1 Header Files 201 9.2.1 Header Files [file.header] The types in all declarations of the same object, function, class, etc., must be consistent. Conse- quently, the source code submitted to the compiler and later linked together must be consistent. One imperfect but simple method of achieving consistency for declarations in different translation units is to # i in nc cl read more..

  • Page - 213

    202 Source Files and Programs Chapter 9 _ _____________________________________________________________________ Ordinary function definitions c ch ha ar r g ge et t(c ch ha ar r* p p) { r re et tu ur rn n * p p++; } Data definitions i in nt t a a; Aggregate definitions s sh ho or rt t t tb bl l[] = { 1 1, 2 2, 3 3 }; Unnamed namespaces n na am me es sp pa read more..

  • Page - 214

    Section 9.2.2 Standard Library Headers 203 # i if fd de ef f _ __ _c cp pl lu us sp pl lu us s } } u us si in ng g n na am me es sp pa ac ce e s st td d; / / make stdio available in global namespace # e en nd di if f That is, the actual declarations are (most likely) shared, but linkage and namespace issues must be addressed to allow C and read more..

  • Page - 215

    204 Source Files and Programs Chapter 9 / / file1.c: # i in nc cl lu ud de e " s s.h h" / / use f() here / / file2.c: # i in nc cl lu ud de e " s s.h h" v vo oi id d f f(S S* p p) { /* ... */ } or graphically: s st tr ru uc ct t S S { i in nt t a a; c ch ha ar r b b; }; v vo oi id d f f(S S*); # i in nc read more..

  • Page - 216

    Section 9.2.3 The One-Definition Rule 205 / / file s.h: s st tr ru uc ct t S S { P Po oi in nt t a a; c ch ha ar r b b; }; / / file1.c: # d de ef fi in ne e P Po oi in nt t i in nt t # i in nc cl lu ud de e " s s.h h" / / ... / / file2.c: c cl la as ss s P Po oi in nt t { /* ... */ }; # i in nc cl lu ud de read more..

  • Page - 217

    206 Source Files and Programs Chapter 9 An e ex xt te er rn n " "C C" " directive specifies the linkage convention (only) and does not affect the seman- tics of calls to the function. In particular, a function declared e ex xt te er rn n " "C C" " still obeys the C++ type checking and argument conversion rules and not the weaker read more..

  • Page - 218

    Section 9.2.4 Linkage to Non-C++ Code 207 – and is still defined rather than just declared. To declare but not define a variable, you must apply the keyword e ex xt te er rn n directly in the declaration. For example: e ex xt te er rn n " C C" i in nt t g g3 3; / / declaration, not definition This looks odd at first glance. However, it is a read more..

  • Page - 219

    208 Source Files and Programs Chapter 9 v vo oi id d f f(c ch ha ar r* v v, i in nt t s sz z) { q qs so or rt t(v v,s sz z,1 1,&c co om mp pa ar re e) ; / / error q qs so or rt t(v v,s sz z,1 1,&c cc cm mp p) ; / / ok i is so or rt t(v v,s sz z,1 1,&c co om mp pa ar re e) ; / / ok i is so or rt t(v v,s sz read more..

  • Page - 220

    Section 9.3.1 Single Header File 209 T To ok ke en n _ _v va al lu ue e g ge et t _ _t to ok ke en n() ; } n na am me es sp pa ac ce e P Pa ar rs se er r { d do ou ub bl le e p pr ri im m(b bo oo ol l g ge et t) ; / / handle primaries d do ou ub bl le e t te er rm m(b bo oo ol l g ge et t) ; / / multiply and read more..

  • Page - 221

    210 Source Files and Programs Chapter 9 the linker will catch the problem. If a declaration is missing, some . c c file will fail to compile. File p pa ar rs se er r.c c will look like this: / / parser.c: # i in nc cl lu ud de e " d dc c.h h" d do ou ub bl le e P Pa ar rs se er r: : p pr ri im m(b bo oo ol l g ge et t) { /* read more..

  • Page - 222

    Section 9.3.1 Single Header File 211 programs, the structure can be simplified by moving all # i in nc cl lu ud de e directives to the common header. This single-header style of physical partitioning is most useful when the program is small and its parts are not intended to be used separately. Note that when namespaces are used, the logical structure of the program is read more..

  • Page - 223

    212 Source Files and Programs Chapter 9 / / parser.c: # i in nc cl lu ud de e " p pa ar rs se er r _ _i im mp pl l.h h" # i in nc cl lu ud de e " t ta ab bl le e.h h" d do ou ub bl le e P Pa ar rs se er r: : p pr ri im m(b bo oo ol l g ge et t) { /* ... */ } d do ou ub bl le e P Pa ar rs se er r: read more..

  • Page - 224

    Section 9.3.2 Multiple Header Files 213 and modifying a large program, it is essential for a programmer to focus on a relatively small chunk of code. The multiple-header organization makes it easy to determine exactly what the parser code depends on and to ignore the rest of the program. The single-header approach forces us to look at every declaration used by any module and read more..

  • Page - 225

    214 Source Files and Programs Chapter 9 In addition to l le ex xe er r.h h, the implementation of the lexer depends on e er rr ro or r.h h, < i io os st tr re ea am m>, and the functions determining the kinds of characters declared in < c cc ct ty yp pe e>: / / lexer.c: # i in nc cl lu ud de e " l le ex xe er r.h h" # i in nc read more..

  • Page - 226

    Section 9.3.2.1 Other Calculator Modules 215 # i in nc cl lu ud de e < s ss st tr re ea am m> i in nt t m ma ai in n(i in nt t a ar rg gc c, c ch ha ar r* a ar rg gv v[]) { /* ... */ } Because the D Dr ri iv ve er r namespace is used exclusively by m ma ai in n(), I placed it in m ma ai in n.c c. Alterna- tively, I could read more..

  • Page - 227

    216 Source Files and Programs Chapter 9 9.3.3 Include Guards [file.guards] The idea of the multiple-header approach is to represent each logical module as a consistent, self- contained unit. Viewed from the program as a whole, many of the declarations needed to make each logical module complete are redundant. For larger programs, such redundancy can lead to errors, as a header read more..

  • Page - 228

    Section 9.4 Programs 217 9.4 Programs [file.programs] A program is a collection of separately compiled units combined by a linker. Every function, object, type, etc., used in this collection must have a unique definition (§4.9, §9.2.3). The program must contain exactly one function called m ma ai in n() (§3.2). The main computation performed by the program starts with the read more..

  • Page - 229

    218 Source Files and Programs Chapter 9 implementation uses to start up a C++ program. This mechanism is guaranteed to work properly only if m ma ai in n() is executed. Consequently, one should avoid nonlocal variables that require run- time initialization in C++ code intended for execution as a fragment of a non-C++ program. Note that variables initialized by constant read more..

  • Page - 230

    Section 9.4.1.1 Program Termination 219 result. Also, there is an implementation-defined limit to the number of atexit functions; a at te ex xi it t() indicates when that limit is reached by returning a nonzero value. These limitations make a at te ex xi it t() less useful than it appears at first glance. The destructor of an object created before a call of a at te read more..

  • Page - 231

    220 Source Files and Programs Chapter 9 7. ( ∗3) Open and read 100 files containing 1500 characters each. Open and read one file contain- ing 150,000 characters. Hint: See example in §21.5.1. Is there a performance difference? What is the highest number of files that can be simultaneously open on your system? Consider these questions in relation to the use of # i in nc read more..

  • Page - 232

    Part II Abstraction Mechanisms This part describes C++’s facilities for defining and using new types. Techniques com- monly called object-oriented programming and generic programming are presented. Chapters 10 Classes 11 Operator Overloading 12 Derived Classes 13 Templates 14 Exception Handling 15 Class Hierarchies The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by read more..

  • Page - 233

    222 Abstraction Mechanisms Part II ‘‘... there is nothing more difficult to carry out, nor more doubtful of success, nor more dangerous to handle, than to initiate a new order of things. For the reformer makes enemies of all those who profit by the old order, and only lukewarm defenders in all those who would profit by the new order...’’ — Nicollo Machiavelli (‘‘The Prince’’ read more..

  • Page - 234

    _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 10 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Classes Those types are not "abstract"; they are as read more..

  • Page - 235

    224 Classes Chapter 10 The fundamental idea in defining a new type is to separate the incidental details of the imple- mentation (e.g., the layout of the data used to store an object of the type) from the properties essen- tial to the correct use of it (e.g., the complete list of functions that can access the data). Such a sep- aration is best expressed by channeling read more..

  • Page - 236

    Section 10.2.1 Member Functions 225 t to od da ay y.i in ni it t(1 16 6,1 10 0,1 19 99 96 6) ; m my y _ _b bi ir rt th hd da ay y.i in ni it t(3 30 0,1 12 2,1 19 95 50 0) ; D Da at te e t to om mo or rr ro ow w = t to od da ay y; t to om mo or rr ro ow w.a ad dd d _ _d da ay y(1 1) ; / / ... } Because different read more..

  • Page - 237

    226 Classes Chapter 10 of the class. A s st tr ru uc ct t is simply a c cl la as ss s whose members are public by default (§10.2.8); member functions can be defined and used exactly as before. For example: i in nl li in ne e v vo oi id d D Da at te e: : a ad dd d _ _y ye ea ar r(i in nt t n n) { y y += n n; } However, nonmember functions read more..

  • Page - 238

    Section 10.2.3 Constructors 227 D Da at te e t to od da ay y = D Da at te e(2 23 3,6 6,1 19 98 83 3) ; D Da at te e x xm ma as s(2 25 5,1 12 2,1 19 99 90 0) ; / / abbreviated form D Da at te e m my y _ _b bi ir rt th hd da ay y; / / error: initializer missing D Da at te e r re el le ea as se e1 1 _ _0 0(1 10 0,1 12 read more..

  • Page - 239

    228 Classes Chapter 10 may not be an obvious choice. Fortunately, there is no year zero on the European calendar; 1AD (y ye ea ar r==1 1) comes immediately after 1BC (y ye ea ar r==-1 1). 10.2.4 Static Members [class.static] The convenience of a default value for D Da at te es was bought at the cost of a significant hidden prob- lem. Our D Da at te e class read more..

  • Page - 240

    Section 10.2.4 Static Members 229 D Da at te e D Da at te e: : d de ef fa au ul lt t _ _d da at te e(1 16 6,1 12 2,1 17 77 70 0) ; v vo oi id d D Da at te e: : s se et t _ _d de ef fa au ul lt t(i in nt t d d, i in nt t m m, i in nt t y y) { D Da at te e: : d de ef fa au ul lt t _ _d da at te e = D Da read more..

  • Page - 241

    230 Classes Chapter 10 Naturally, the compiler will catch accidental attempts to violate this promise. For example: i in nl li in ne e i in nt t D Da at te e: : y ye ea ar r() c co on ns st t { r re et tu ur rn n y y++; / / error: attempt to change member value in const function } When a c co on ns st t member function is defined outside its read more..

  • Page - 242

    Section 10.2.7 Self-Reference 231 D Da at te e& a ad dd d _ _y ye ea ar r(i in nt t n n) ; / / add n years D Da at te e& a ad dd d _ _m mo on nt th h(i in nt t n n) ; / / add n months D Da at te e& a ad dd d _ _d da ay y(i in nt t n n) ; / / add n days }; Each (nonstatic) member function knows what object it was read more..

  • Page - 243

    232 Classes Chapter 10 D Da at te e’s value had been changed. Caching values like that is more common for more complicated data structures, but let’s see how it can be achieved for a D Da at te e: c cl la as ss s D Da at te e { b bo oo ol l c ca ac ch he e _ _v va al li id d; s st tr ri in ng g c ca ac ch he e; v vo oi id d read more..

  • Page - 244

    Section 10.2.7.2 Mutable 233 c cl la as ss s D Da at te e { m mu ut ta ab bl le e b bo oo ol l c ca ac ch he e _ _v va al li id d; m mu ut ta ab bl le e s st tr ri in ng g c ca ac ch he e; v vo oi id d c co om mp pu ut te e _ _c ca ac ch he e _ _v va al lu ue e() c co on ns st t; / / fill (mutable) cache read more..

  • Page - 245

    234 Classes Chapter 10 s st tr ri in ng g D Da at te e: : s st tr ri in ng g _ _r re ep p() c co on ns st t { i if f (! c c->v va al li id d) { c co om mp pu ut te e _ _c ca ac ch he e _ _v va al lu ue e() ; c c->v va al li id d = t tr ru ue e; } r re et tu ur rn n c c->r re ep p; } The programming read more..

  • Page - 246

    Section 10.2.8 Structures and Classes 235 v vo oi id d a ad dd d _ _y ye ea ar r(i in nt t n n) ; / / add n years p pr ri iv va at te e: i in nt t d d, m m, y y; }; In real code, where both the public interface and the implementation details typically are more extensive than in tutorial examples, I usually prefer the style used for D Da at te read more..

  • Page - 247

    236 Classes Chapter 10 c cl la as ss s D Da at te e { p pu ub bl li ic c: i in nt t d da ay y() c co on ns st t; / / ... p pr ri iv va at te e: i in nt t d d, m m, y y; }; i in nl li in ne e i in nt t D Da at te e: : d da ay y() c co on ns st t { r re et tu ur rn n d d; } 10.3 Efficient User-Defined Types read more..

  • Page - 248

    Section 10.3 Efficient User-Defined Types 237 s st tr ri in ng g s st tr ri in ng g _ _r re ep p() c co on ns st t; / / string representation v vo oi id d c ch ha ar r _ _r re ep p(c ch ha ar r s s[]) c co on ns st t; / / C-style string representation s st ta at ti ic c v vo oi id d s se et t _ _d de ef fa au ul lt t(i in read more..

  • Page - 249

    238 Classes Chapter 10 This assumes that the output operator << and the addition operator + have been declared for D Da at te es. I do that in §10.3.3. Note the D Da at te e: : f fe eb b notation. The function f f() is not a member of D Da at te e, so it must specify that it is referring to D Da at te e’s f fe eb b and not to some other read more..

  • Page - 250

    Section 10.3.1 Member Functions 239 i if f ( d dd d<1 1 || m ma ax x<d dd d) t th hr ro ow w B Ba ad d _ _d da at te e() ; y y = y yy y; m m = m mm m; d d = d dd d; } The constructor checks that the data supplied denotes a valid D Da at te e. If not, say for D Da at te e(3 30 0,D Da at te e: : f fe eb b,1 19 99 94 4), read more..

  • Page - 251

    240 Classes Chapter 10 D Da at te e& D Da at te e: : a ad dd d _ _m mo on nt th h(i in nt t n n) { i if f ( n n==0 0) r re et tu ur rn n * t th hi is s; i if f ( n n>0 0) { i in nt t d de el lt ta a _ _y y = n n/1 12 2; i in nt t m mm m = m m+n n%1 12 2; i if f ( 1 12 2 < m mm m) { / / note: read more..

  • Page - 252

    Section 10.3.2 Helper Functions 241 i in nt t d di if ff f(D Da at te e a a, D Da at te e b b) ; b bo oo ol l l le ea ap py ye ea ar r(i in nt t y y) ; D Da at te e n ne ex xt t _ _w we ee ek kd da ay y(D Da at te e d d) ; D Da at te e n ne ex xt t _ _s sa at tu ur rd da ay y(D Da at te e d d) ; / / read more..

  • Page - 253

    242 Classes Chapter 10 The intent of a concrete type is to do a single, relatively small thing well and efficiently. It is not usually the aim to provide the user with facilities to modify the behavior of a concrete type. In particular, concrete types are not intended to display polymorphic behavior (see §2.5.5, §12.2.6). If you don’t like some detail of a concrete type, read more..

  • Page - 254

    Section 10.4.1 Destructors 243 implicitly when an automatic variable goes out of scope, an object on the free store is deleted, etc. Only in very unusual circumstances does the user need to call a destructor explicitly (§10.4.11). The most common use of a destructor is to release memory acquired in a constructor. Consider a simple table of elements of some type N Na am me read more..

  • Page - 255

    244 Classes Chapter 10 T Ta ab bl le es s t tt t; Here, t tt t will be initialized using a generated default constructor that calls T Ta ab bl le e(1 15 5) for t tt t.t t1 1 and each element of t tt t.v vt t. On the other hand, t tt t.i i and the elements of t tt t.v vi i are not initialized because those objects are not of a class type. The read more..

  • Page - 256

    Section 10.4.4 Local Variables 245 10.4.4 Local Variables [class.local] The constructor for a local variable is executed each time the thread of control passes through the declaration of the local variable. The destructor for a local variable is executed each time the local variable’s block is exited. Destructors for local variables are executed in reverse order of their con- read more..

  • Page - 257

    246 Classes Chapter 10 Such anomalies can be avoided by defining what it means to copy a T Ta ab bl le e: c cl la as ss s T Ta ab bl le e { / / ... T Ta ab bl le e(c co on ns st t T Ta ab bl le e&) ; / / copy constructor T Ta ab bl le e& o op pe er ra at to or r=(c co on ns st t T Ta ab bl le e&) ; / / copy read more..

  • Page - 258

    Section 10.4.5 Free Store 247 deleted twice and the object pointed to by q q not at all. Not deleting an object is typically not an error as far as the language is concerned; it is only a waste of space. However, in a program that is meant to run for a long time, such a memory leak is a serious and hard-to-find error. There are tools available for detecting read more..

  • Page - 259

    248 Classes Chapter 10 If a member constructor needs no arguments, the member need not be mentioned in the member initializer list, so C Cl lu ub b: : C Cl lu ub b(c co on ns st t s st tr ri in ng g& n n, D Da at te e f fd d) : n na am me e(n n) , f fo ou un nd de ed d(f fd d) { / / ... } is equivalent to the previous version. In read more..

  • Page - 260

    Section 10.4.6.1 Necessary Member Initialization 249 Here n na am me e is initialized with a copy of n n. On the other hand, a ad dd dr re es ss s is first initialized to the empty string and then a copy of a a is assigned. 10.4.6.2 Member Constants [class.memconst] It is also possible to initialize a static integral constant member by adding a constant-expression read more..

  • Page - 261

    250 Classes Chapter 10 Y Y y y1 1; Y Y y y2 2 = y y1 1; / / error: cannot copy Y::a In addition, a default assignment cannot be generated if a nonstatic member is a reference, a c co on ns st t, or a user-defined type without a copy assignment. Note that the default copy constructor leaves a reference member referring to the same object in both the original read more..

  • Page - 262

    Section 10.4.7 Arrays 251 v vo oi id d f f(i in nt t s sz z) { T Ta ab bl le e* t t1 1 = n ne ew w T Ta ab bl le e; T Ta ab bl le e* t t2 2 = n ne ew w T Ta ab bl le e[s sz z] ; T Ta ab bl le e* t t3 3 = n ne ew w T Ta ab bl le e; T Ta ab bl le e* t t4 4 = n ne ew w T Ta ab bl le e[s sz z] ; d de read more..

  • Page - 263

    252 Classes Chapter 10 i in nt t m ma ai in n() { f f(0 0) ; f f(1 1) ; f f(2 2) ; / / ... } Here, the constructor is called for t tb bl l once the first time f f() is called. Because t tb bl l is declared s st ta at ti ic c, it does not get destroyed on return from f f() and it does not get constructed a second time when f f() is called read more..

  • Page - 264

    Section 10.4.9 Nonlocal Store 253 Whether t tb bl l1 1 is constructed before t tb bl l2 2 or vice versa is implementation-dependent. The order isn’t even guaranteed to be fixed in every particular implementation. Dynamic linking, or even a small change in the compilation process, can alter the sequence. The order of destruction is similarly implementation-dependent. Sometimes when read more..

  • Page - 265

    254 Classes Chapter 10 objects are necessary, they must be constructed carefully in stages. Also, there is no similarly sim- ple last-time switch construct. Instead, see §9.4.1.1 and §21.5.2. 10.4.10 Temporary Objects [class.temp] Temporary objects most often are the result of arithmetic expressions. For example, at some point in the evaluation of x x*y y+z z the partial result x x*y read more..

  • Page - 266

    Section 10.4.10 Temporary Objects 255 v vo oi id d f f(s st tr ri in ng g& s s1 1, s st tr ri in ng g& s s2 2, s st tr ri in ng g& s s3 3) { c co ou ut t << s s1 1+s s2 2; s st tr ri in ng g s s = s s2 2+s s3 3; i if f ( s s.l le en ng gt th h()<8 8 && s s[0 0]==´a a´) { / / use s here } } A read more..

  • Page - 267

    256 Classes Chapter 10 Because of this usage, the n ne ew w(b bu uf f)X X syntax for supplying extra arguments to o op pe er ra at to or r n ne ew w() is known as the placement syntax. Note that every o op pe er ra at to or r n ne ew w() takes a size as its first argument and that the size of the object allocated is implicitly supplied (§15.6). read more..

  • Page - 268

    Section 10.4.11 Placement of Objects 257 calling a destructor explicitly and also should ask a more experienced colleague before doing so. See §14.4.7 for an explanation of how placement new interacts 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, a special o op pe er ra at to read more..

  • Page - 269

    258 Classes Chapter 10 [15] When adding a new member to a class, always check to see if there are user-defined construc- tors that need to be updated to initialize the member; §10.4.6.3. [16] Use enumerators when you need to define integer constants in class declarations; §10.4.6.1. [17] Avoid order dependencies when constructing global and namespace objects; §10.4.9. [18] Use read more..

  • Page - 270

    Section 10.6 Exercises 259 of the expression on c co ou ut t. A program might look like this: E Ex xp pr r x x("1 12 23 3/4 4+1 12 23 3*4 4-3 3") ; c co ou ut t << " x x = " << x x.e ev va al l() << " \ \n n"; x x.p pr ri in nt t() ; Define class E Ex xp pr r twice: once using a linked list of read more..

  • Page - 271

    260 Classes Chapter 10 The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved. read more..

  • Page - 272

    _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 11 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Operator Overloading When I use a word it means just read more..

  • Page - 273

    262 Operator Overloading Chapter 11 for such classes sometimes allows a programmer to provide a more conventional and convenient notation for manipulating objects than could be achieved using only the basic functional notation. For example, c cl la as ss s c co om mp pl le ex x { / / very simplified complex d do ou ub bl le e r re e, i im m; p pu ub bl li ic read more..

  • Page - 274

    Section 11.2 Operator Functions 263 They take a name, rather than a value, as their second operand and provide the primary means of referring to members. Allowing them to be overloaded would lead to subtleties [Stroustrup,1994]. It is not possible to define new operator tokens, but you can use the function-call notation when this set of operators is not adequate. For example, read more..

  • Page - 275

    264 Operator Overloading Chapter 11 any, interpretation is used. An operator can be declared only for the syntax defined for it in the grammar (§A.5). For example, a user cannot define a unary % or a ternary + . Consider: c cl la as ss s X X { / / members (with implicit ‘this’ pointer): X X* o op pe er ra at to or r&() ; / / prefix unary & (address read more..

  • Page - 276

    Section 11.2.2 Predefined Meanings for Operators 265 v vo oi id d f f(X X a a, X X b b) { a a = b b; / / error: operator= private & a a; / / error: operator& private a a,b b; / / error: operator, private } Alternatively, they can be given new meanings by suitable definitions. 11.2.3 Operators and User-Defined Types [over.user] An operator function must either be read more..

  • Page - 277

    266 Operator Overloading Chapter 11 c cl la as ss s s st tr ri in ng g { / / ... }; o os st tr re ea am m& o op pe er ra at to or r<<(o os st tr re ea am m&, c co on ns st t s st tr ri in ng g&) ; } i in nt t m ma ai in n() { c ch ha ar r* p p = " H He el ll lo o"; s st td d: : s st tr ri read more..

  • Page - 278

    Section 11.2.4 Operators in Namespaces 267 (§7.4) are used to find the best match, if any. This lookup mechanism is applied only if the opera- tor has at least one operand of a user-defined type. Therefore, user-defined conversions (§11.3.2, §11.4) will be considered. Note that a t ty yp pe ed de ef f name is just a synonym and not a user-defined type (§4.9.7). 11.3 A Complex Number read more..

  • Page - 279

    268 Operator Overloading Chapter 11 v vo oi id d f f(c co om mp pl le ex x x x, c co om mp pl le ex x y y, c co om mp pl le ex x z z) { c co om mp pl le ex x r r1 1 = x x+y y+z z; / / r1 = operator+(x,operator+(y,z)) c co om mp pl le ex x r r2 2 = x x; / / r2 = x r r2 2 += y y; / / r2.operator+=(y) r r2 2 += z z; / read more..

  • Page - 280

    Section 11.3.2 Mixed-Mode Arithmetic 269 c co om mp pl le ex x& o op pe er ra at to or r+=(d do ou ub bl le e a a) { r re e += a a; r re et tu ur rn n * t th hi is s; } / / ... }; c co om mp pl le ex x o op pe er ra at to or r+(c co om mp pl le ex x a a, c co om mp pl le ex x b b) { c co om mp pl le ex x r read more..

  • Page - 281

    270 Operator Overloading Chapter 11 c cl la as ss s c co om mp pl le ex x { d do ou ub bl le e r re e, i im m; p pu ub bl li ic c: c co om mp pl le ex x(d do ou ub bl le e r r) : r re e(r r) , i im m(0 0) { } / / ... }; The constructor specifies the traditional embedding of the real line in the complex plane. A constructor is a read more..

  • Page - 282

    Section 11.3.4 Copying 271 11.3.4 Copying [over.copy] In addition to the explicitly declared constructors, c co om mp pl le ex x by default gets a copy constructor defined (§10.2.5). A default copy constructor simply copies all members. To be explicit, we could equivalently have written: c cl la as ss s c co om mp pl le ex x { d do ou ub bl le e r re e, i read more..

  • Page - 283

    272 Operator Overloading Chapter 11 11.3.5 Constructors and Conversions [over.conv] We defined three versions of each of the four standard arithmetic operators: c co om mp pl le ex x o op pe er ra at to or r+(c co om mp pl le ex x,c co om mp pl le ex x) ; c co om mp pl le ex x o op pe er ra at to or r+(c co om mp pl le ex x,d do ou ub bl read more..

  • Page - 284

    Section 11.3.6 Literals 273 11.3.6 Literals [over.literals] It is not possible to define literals of a class type in the sense that 1 1.2 2 and 1 12 2e e3 3 are literals of type d do ou ub bl le e. However, literals of the basic types can often be used instead if class member functions are used to provide an interpretation for them. Constructors taking a single read more..

  • Page - 285

    274 Operator Overloading Chapter 11 c cl la as ss s c co om mp pl le ex x { d do ou ub bl le e r re e, i im m; p pu ub bl li ic c: c co om mp pl le ex x(d do ou ub bl le e r r = 0 0, d do ou ub bl le e i i = 0 0) : r re e(r r) , i im m(i i) { } d do ou ub bl le e r re ea al l() c co on ns st t { r re read more..

  • Page - 286

    Section 11.4 Conversion Operators 275 11.4 Conversion Operators [over.conversion] Using a constructor to specify type conversion is convenient but has implications that can be unde- sirable. A constructor cannot specify [1] an implicit conversion from a user-defined type to a basic type (because the basic types are not classes), or [2] a conversion from a new class to a previously read more..

  • Page - 287

    276 Operator Overloading Chapter 11 Conversion functions appear to be particularly useful for handling data structures when reading (implemented by a conversion operator) is trivial, while assignment and initialization are distinctly less trivial. The i is st tr re ea am m and o os st tr re ea am m types rely on a conversion function to enable statements such as w wh hi read more..

  • Page - 288

    Section 11.4.1 Ambiguities 277 v vo oi id d k k1 1() { f f(1 1) ; / / error: ambiguous f(X(1)) or f(Y(1))? f f(X X(1 1)) ; / / ok f f(Y Y(1 1)) ; / / ok g g("M Ma ac ck k") ; / / error: two user-defined conversions needed; g(Z(X("Mack"))) not tried g g(X X("D Do oc c")) ; / / ok: g(Z(X("Doc"))) g g(Z Z("S Su uz zy read more..

  • Page - 289

    278 Operator Overloading Chapter 11 c cl la as ss s R Re ea al l { p pu ub bl li ic c: o op pe er ra at to or r d do ou ub bl le e() ; o op pe er ra at to or r i in nt t() ; / / ... }; v vo oi id d g g(R Re ea al l a a) { d do ou ub bl le e d d = a a; / / d = a.double(); i in nt t i i = a a; / / i = read more..

  • Page - 290

    Section 11.5 Friends 279 V Ve ec ct to or r o op pe er ra at to or r*(c co on ns st t M Ma at tr ri ix x& m m, c co on ns st t V Ve ec ct to or r& v v) { V Ve ec ct to or r r r; f fo or r ( i in nt t i i = 0 0; i i<4 4; i i++) { / / r[i] = m[i] * v; r r.v v[i i] = 0 0; f fo or r ( i in nt t j read more..

  • Page - 291

    280 Operator Overloading Chapter 11 enclosing scope. For a template class that can be instantiated in many different contexts (Chapter 13), this is very important. A friend class must be previously declared in an enclosing scope or defined in the non-class scope immediately enclosing the class that is declaring it a friend. For example: c cl la as ss s X X { /* ... */ }; read more..

  • Page - 292

    Section 11.5.2 Friends and Members 281 functions (§12.2.6) – but typically there is a choice. Because member names are local to the class, a function should be a member unless there is a specific reason for it to be a nonmember. Consider a class X X presenting alternative ways of presenting an operation: c cl la as ss s X X { / / ... X X(i in nt t) ; i in read more..

  • Page - 293

    282 Operator Overloading Chapter 11 notation i in nv v(m m) for inverting a M Ma at tr ri ix x m m to the alternative m m.i in nv v(). Naturally, if i in nv v() really does invert m m itself, rather than return a new M Ma at tr ri ix x that is the inverse of m m, it should be a member. All other things considered equal, choose a member. It is not read more..

  • Page - 294

    Section 11.6 Large Objects 283 This is legal, but it causes a memory allocation problem. Because a reference to the result will be passed out of the function as a reference to the return value, the return value cannot be an automatic variable (§7.3). Since an operator is often used more than once in an expression, the result cannot be a s st ta at ti ic c local read more..

  • Page - 295

    284 Operator Overloading Chapter 11 c cl la as ss s X X { / / ... X X(S So om me et ty yp pe e) ; / / constructor: create objects X X(c co on ns st t X X&) ; / / copy constructor X X& o op pe er ra at to or r=(c co on ns st t X X&) ; / / copy assignment: cleanup and copy ~ X X() ; / / destructor: cleanup }; There are three more read more..

  • Page - 296

    Section 11.7.1 Explicit Constructors 285 c cl la as ss s S St tr ri in ng g { / / ... e ex xp pl li ic ci it t S St tr ri in ng g(i in nt t n n) ; / / preallocate n bytes S St tr ri in ng g(c co on ns st t c ch ha ar r* p p) ; / / initial value is the C-style string p }; S St tr ri in ng g s s1 1 = ´ a a´; / / error: read more..

  • Page - 297

    286 Operator Overloading Chapter 11 The Y Ye ea ar r class is a simple ‘‘wrapper’’ around an i in nt t. Thanks to the o op pe er ra at to or r i in nt t(), a Y Ye ea ar r is implicitly converted into an i in nt t wherever needed. By declaring the constructor e ex xp pl li ic ci it t, we make sure that the i in nt t to Y Ye ea ar r read more..

  • Page - 298

    Section 11.8 Subscripting 287 v vo oi id d A As ss so oc c: : p pr ri in nt t _ _a al ll l() c co on ns st t { f fo or r ( v ve ec ct to or r<P Pa ai ir r>: : c co on ns st t _ _i it te er ra at to or r p p = v ve ec c.b be eg gi in n() ; p p!=v ve ec c.e en nd d() ; ++ p p) c co ou ut t << p p->n read more..

  • Page - 299

    288 Operator Overloading Chapter 11 v vo oi id d a ad dd d2 23 3(c co om mp pl le ex x& c c) { c c += c co om mp pl le ex x(2 2,3 3) ; } v vo oi id d g g(v ve ec ct to or r<c co om mp pl le ex x>& a aa a, l li is st t<c co om mp pl le ex x>& l ll l) { f fo or r _ _e ea ac ch h(a aa a.b be eg gi read more..

  • Page - 300

    Section 11.9 Function Call 289 Other popular uses of o op pe er ra at to or r()() are as a substring operator and as a subscripting operator for multidimensional arrays (§22.4.5). An o op pe er ra at to or r()() must be a member function. 11.10 Dereferencing [over.deref] The dereferencing operator -> can be defined as a unary postfix operator. That is, given a class read more..

  • Page - 301

    290 Operator Overloading Chapter 11 R Re ec c* R Re ec c _ _p pt tr r: : o op pe er ra at to or r->() { i if f ( i in n _ _c co or re e _ _a ad dd dr re es ss s == 0 0) i in n _ _c co or re e _ _a ad dd dr re es ss s = r re ea ad d _ _f fr ro om m _ _d di is sk k(i id de en nt ti if fi ie er r) ; r re et read more..

  • Page - 302

    Section 11.10 Dereferencing 291 frequently unused, so it makes sense to postpone checking the constraint on the return type until actual use. 11.11 Increment and Decrement [over.incr] Once people invent ‘‘smart pointers,’’ they often decide to provide the increment operator ++ and the decrement operator -- to mirror these operators’ use for built-in types. This is especially obvi- ous read more..

  • Page - 303

    292 Operator Overloading Chapter 11 c cl la as ss s P Pt tr r _ _t to o _ _T T { T T* p p; T T* a ar rr ra ay y; i in nt t s si iz ze e; p pu ub bl li ic c: P Pt tr r _ _t to o _ _T T(T T* p p, T T* v v, i in nt t s s) ; / / bind to array v of size s, initial value p P Pt tr r _ _t to o _ _T T(T T* p p) ; read more..

  • Page - 304

    Section 11.12 A String Class 293 My almost-real S St tr ri in ng g employs three auxiliary classes: S Sr re ep p, to allow an actual representation to be shared between several S St tr ri in ng gs with the same value; R Ra an ng ge e, to be thrown in case of range errors, and C Cr re ef f, to help implement a subscript operator that distinguishes between read more..

  • Page - 305

    294 Operator Overloading Chapter 11 p pr ri iv va at te e: / / prevent copying: S Sr re ep p(c co on ns st t S Sr re ep p&) ; S Sr re ep p& o op pe er ra at to or r=(c co on ns st t S Sr re ep p&) ; }; Class S St tr ri in ng g provides the usual set of constructors, destructor, and assignment operations: c cl la as ss s S St read more..

  • Page - 306

    Section 11.12 A String Class 295 S St tr ri in ng g: : S St tr ri in ng g(c co on ns st t c ch ha ar r* s s) { r re ep p = n ne ew w S Sr re ep p(s st tr rl le en n(s s) , s s) ; } S St tr ri in ng g& S St tr ri in ng g: : o op pe er ra at to or r=(c co on ns st t c ch ha ar r* s s) { i if f ( r re read more..

  • Page - 307

    296 Operator Overloading Chapter 11 S St tr ri in ng g. Then, and only then, is the representation copied. This technique is usually called copy- on-write. The actual copy is done by S St tr ri in ng g: : S Sr re ep p: : g ge et t _ _o ow wn n _ _c co op py y(). To get these access functions inlined, their definitions must be placed so that the read more..

  • Page - 308

    Section 11.12 A String Class 297 f fr ri ie en nd d b bo oo ol l o op pe er ra at to or r!=(c co on ns st t S St tr ri in ng g& x x, c co on ns st t S St tr ri in ng g& y y) { r re et tu ur rn n s st tr rc cm mp p(x x.r re ep p->s s, y y.r re ep p->s s) != 0 0; } }; S St tr ri in ng g o op pe er read more..

  • Page - 309

    298 Operator Overloading Chapter 11 [11] Make constructors that take a single ‘‘size argument’’ e ex xp pl li ic ci it t; §11.7.1. [12] For non-specialized uses, prefer the standard s st tr ri in ng g (Chapter 20) to the result of your own exercises; §11.12. [13] Be cautious about introducing implicit conversions; §11.4. [14] Use member functions to express operators read more..

  • Page - 310

    Section 11.14 Exercises 299 7. ( ∗2) Define an external iterator for class S St tr ri in ng g: c cl la as ss s S St tr ri in ng g _ _i it te er r { / / refer to string and string element p pu ub bl li ic c: S St tr ri in ng g _ _i it te er r(S St tr ri in ng g& s s) ; / / iterator for s c ch ha ar r& n ne ex xt t() read more..

  • Page - 311

    300 Operator Overloading Chapter 11 20. ( ∗1) Given two structures: s st tr ru uc ct t S S { i in nt t x x, y y; }; s st tr ru uc ct t T T { c ch ha ar r* p p; c ch ha ar r* q q; }; write a class C C that allows the use of x x and p p from some S S and T T, much as if x x and p p had been members of C C. 21. ( ∗1.5) read more..

  • Page - 312

    _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 12 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Derived Classes Do not multiply objects without necessity. read more..

  • Page - 313

    302 Derived Classes Chapter 12 common. Representing a circle and a triangle in a program without involving the notion of a shape would be to lose something essential. This chapter is an exploration of the implications of this sim- ple idea, which is the basis for what is commonly called object-oriented programming. The presentation of language features and techniques progress from read more..

  • Page - 314

    Section 12.2 Derived Classes 303 s st tr ru uc ct t M Ma an na ag ge er r : p pu ub bl li ic c E Em mp pl lo oy ye ee e { s se et t<E Em mp pl lo oy ye ee e*> g gr ro ou up p; s sh ho or rt t l le ev ve el l; / / ... }; The M Ma an na ag ge er r is derived from E Em mp pl lo oy ye ee e, and conversely, E Em read more..

  • Page - 315

    304 Derived Classes Chapter 12 A M Ma an na ag ge er r is (also) an E Em mp pl lo oy ye ee e, so a M Ma an na ag ge er r* can be used as a E Em mp pl lo oy ye ee e*. However, an E Em mp pl lo oy ye ee e is not necessarily a M Ma an na ag ge er r, so an E Em mp pl lo oy ye ee e* cannot be used as a M Ma an na ag read more..

  • Page - 316

    Section 12.2.1 Member Functions 305 c cl la as ss s M Ma an na ag ge er r : p pu ub bl li ic c E Em mp pl lo oy ye ee e { / / ... p pu ub bl li ic c: v vo oi id d p pr ri in nt t() c co on ns st t; / / ... }; A member of a derived class can use the public – and protected (see §15.3) – members of its base class as if they read more..

  • Page - 317

    306 Derived Classes Chapter 12 v vo oi id d M Ma an na ag ge er r: : p pr ri in nt t() c co on ns st t { p pr ri in nt t() ; / / oops! / / print Manager-specific information } and find the program involved in an unexpected sequence of recursive calls. 12.2.2 Constructors and Destructors [derived.ctor] Some derived classes need constructors. If a base class has read more..

  • Page - 318

    Section 12.2.2 Constructors and Destructors 307 M Ma an na ag ge er r: : M Ma an na ag ge er r(c co on ns st t s st tr ri in ng g& n n, i in nt t d d, i in nt t l lv vl l) : f fa am mi il ly y _ _n na am me e(n n) , / / error: family _name not declared in manager d de ep pa ar rt tm me en nt t(d d) , / / error: read more..

  • Page - 319

    308 Derived Classes Chapter 12 c cl la as ss s T Ts se ec c : p pu ub bl li ic c T Te em mp po or ra ar ry y, p pu ub bl li ic c S Se ec cr re et ta ar ry y { /* ... */ }; c cl la as ss s C Co on ns su ul lt ta an nt t : p pu ub bl li ic c T Te em mp po or ra ar ry y, p pu ub bl li ic c M Ma an na read more..

  • Page - 320

    Section 12.2.5 Type Fields 309 s st tr ru uc ct t M Ma an na ag ge er r : p pu ub bl li ic c E Em mp pl lo oy ye ee e { M Ma an na ag ge er r() { t ty yp pe e = M M; } s se et t<E Em mp pl lo oy ye ee e*> g gr ro ou up p; / / people managed s sh ho or rt t l le ev ve el l; / / ... }; Given this, we can now read more..

  • Page - 321

    310 Derived Classes Chapter 12 Finding all such tests on the type field buried in a large function that handles many derived classes can be difficult. Even when they have been found, understanding what is going on can be difficult. Furthermore, any addition of a new kind of E Em mp pl lo oy ye ee e involves a change to all the key functions in the system – the read more..

  • Page - 322

    Section 12.2.6 Virtual Functions 311 v vo oi id d E Em mp pl lo oy ye ee e: : p pr ri in nt t() c co on ns st t { c co ou ut t << f fa am mi il ly y _ _n na am me e << ´ \ \t t´ << d de ep pa ar rt tm me en nt t << ´ \ \n n´; / / ... } A virtual function can be used even if no class is derived from read more..

  • Page - 323

    312 Derived Classes Chapter 12 i in nt t m ma ai in n() { E Em mp pl lo oy ye ee e e e("B Br ro ow wn n",1 12 23 34 4) ; M Ma an na ag ge er r m m("S Sm mi it th h",1 12 23 34 4,2 2) ; s se et t<E Em mp pl lo oy ye ee e*> e em mp pl l; e em mp pl l.p pu us sh h _ _f fr ro on nt t(&e e) ; / read more..

  • Page - 324

    Section 12.3 Abstract Classes 313 12.3 Abstract Classes [derived.abstract] Many classes resemble class E Em mp pl lo oy ye ee e in that they are useful both as themselves and also as bases for derived classes. For such classes, the techniques described in the previous section suffice. However, not all classes follow that pattern. Some classes, such as class S Sh ha ap pe read more..

  • Page - 325

    314 Derived Classes Chapter 12 A pure virtual function that is not defined in a derived class remains a pure virtual function, so the derived class is also an abstract class. This allows us to build implementations in stages: c cl la as ss s P Po ol ly yg go on n : p pu ub bl li ic c S Sh ha ap pe e { / / abstract class p pu ub bl li ic c: b bo read more..

  • Page - 326

    Section 12.4 Design of Class Hierarchies 315 Because there are many ways of implementing this basic idea, we must assume that there will be many different kinds of I Iv va al l _ _b bo ox xe es s, such as sliders, plain boxes in which a user can type a num- ber, dials, and voice interaction. The general approach is to build a ‘‘virtual user-interface system’’ for read more..

  • Page - 327

    316 Derived Classes Chapter 12 e el ls se e { / / old value was fine; do something else } / / ... } v vo oi id d s so om me e _ _f fc ct t() { I Iv va al l _ _b bo ox x* p p1 1 = n ne ew w I Iv va al l _ _s sl li id de er r(0 0,5 5) ; / / Ival _slider derived from Ival _box i in nt te er ra ac ct t(p p1 1) ; I Iv va al read more..

  • Page - 328

    Section 12.4.1 A Traditional Class Hierarchy 317 Bucks Inc.,’’ we would have to make each of our I Iv va al l _ _s sl li id de er r, I Iv va al l _ _d di ia al l, etc., classes a kind of B BB Bw wi in nd do ow w. This would most simply be achieved by rewriting our I Iv va al l _ _b bo ox x so that it derives from B BB Bw wi in nd do ow w. read more..

  • Page - 329

    318 Derived Classes Chapter 12 asking for trouble. Sooner or later someone will get them out of sync. Also, experience shows that novice programmers tend to mess with protected data in ways that are unnecessary and that cause maintenance problems. Data is better kept private so that writers of derived classes cannot mess with them. Better still, data should be in the derived read more..

  • Page - 330

    Section 12.4.2 Abstract Classes 319 c cl la as ss s I Iv va al l _ _s sl li id de er r : p pu ub bl li ic c I Iv va al l _ _b bo ox x, p pr ro ot te ec ct te ed d B BB Bw wi in nd do ow w { p pu ub bl li ic c: I Iv va al l _ _s sl li id de er r(i in nt t,i in nt t) ; ~ I Iv va al l _ _s sl li id de er read more..

  • Page - 331

    320 Derived Classes Chapter 12 The I Iv va al l _ _b bo ox x hierarchy can now be defined like this: c cl la as ss s I Iv va al l _ _b bo ox x { /* ... */ }; c cl la as ss s I Iv va al l _ _s sl li id de er r : p pu ub bl li ic c I Iv va al l _ _b bo ox x, p pr ro ot te ec ct te ed d B BB Bw wi in nd do ow w read more..

  • Page - 332

    Section 12.4.3 Alternative Implementations 321 c cl la as ss s B BB B _ _i iv va al l _ _s sl li id de er r : p pu ub bl li ic c I Iv va al l _ _s sl li id de er r, p pr ro ot te ec ct te ed d B BB Bw wi in nd do ow w { /* ... */ }; c cl la as ss s C CW W _ _i iv va al l _ _s sl li id de er r : p pu ub bl read more..

  • Page - 333

    322 Derived Classes Chapter 12 Using obvious abbreviations, this hierarchy can be represented graphically like this: I Iv va al l _ _b bo ox x I Iv va al l _ _s sl li id de er r I Iv va al l _ _d di ia al l i if fl la as sh h i ip po op pu up p C CW Ws sl l C CW Ws sl l C CW Ws sl l C CW Wi is sl li id de er r B BB Bi is read more..

  • Page - 334

    Section 12.4.4 Localizing Object Creation 323 done using implementation-specific names such as C CW W _ _i iv va al l _ _d di ia al l and B BB B _ _f fl la as sh hi in ng g _ _i iv va al l _ _s sl li id de er r. We would like to minimize the number of places where such specific names occur, and object cre- ation is hard to localize unless it is read more..

  • Page - 335

    324 Derived Classes Chapter 12 B BB B _ _m ma ak ke er r B BB B _ _i im mp pl l; / / for BB users L LS S _ _m ma ak ke er r L LS S _ _i im mp pl l; / / for LS users v vo oi id d d dr ri iv ve er r() { u us se er r(&B BB B _ _i im mp pl l) ; / / use BB u us se er r(&L LS S _ _i im mp pl l) ; / / use LS } read more..

  • Page - 336

    Section 12.7 Exercises 325 12.7 Exercises [derived.exercises] 1. ( ∗1) Define c cl la as ss s b ba as se e { p pu ub bl li ic c: v vi ir rt tu ua al l v vo oi id d i ia am m() { c co ou ut t << " b ba as se e\ \n n"; } }; Derive two classes from b ba as se e, and for each define i ia am m() to write out the name of read more..

  • Page - 337

    326 Derived Classes Chapter 12 c cl la as ss s C Ch ha ar r _ _v ve ec c { i in nt t s sz z; c ch ha ar r e el le em me en nt t[1 1] ; p pu ub bl li ic c: s st ta at ti ic c C Ch ha ar r _ _v ve ec c* n ne ew w _ _c ch ha ar r _ _v ve ec c(i in nt t s s) ; c ch ha ar r& o op pe er ra at to or r[](i read more..

  • Page - 338

    _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 13 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Templates Your quote here. – B. Stroustrup Templates — a read more..

  • Page - 339

    328 Templates Chapter 13 sophisticated implementations behind simple interfaces and to expose complexity to the user only when the user has a specific need for it. For example, s so or rt t(v v) can be the interface to a variety of sort algorithms for elements of a variety of types held in a variety of containers. The sort function that is most appropriate for the read more..

  • Page - 340

    Section 13.2 A Simple String Template 329 The name of a class template followed by a type bracketed by < > is the name of a class (as defined by the template) and can be used exactly like other class names. For example: S St tr ri in ng g<c ch ha ar r> c cs s; S St tr ri in ng g<u un ns si ig gn ne ed d c ch ha ar r> u us s; S read more..

  • Page - 341

    330 Templates Chapter 13 Also, we often prefer not to know the details of how a type is defined, and a t ty yp pe ed de ef f allows us to hide the fact that a type is generated from a template. 13.2.1 Defining a Template [temp.string.details] A class generated from a class template is a perfectly ordinary class. Thus, use of a template does not imply any run-time read more..

  • Page - 342

    Section 13.2.1 Defining a Template 331 overloading is a possibility for functions only (§13.3.2), while specialization (§13.5) enables us to provide alternative implementations for a template. It is not possible to overload a class template name, so if a class template is declared in a scope, no other entity can be declared there with the same name (see also §13.5). For example: read more..

  • Page - 343

    332 Templates Chapter 13 t te em mp pl la at te e<c cl la as ss s T T, i in nt t i i> c cl la as ss s B Bu uf ff fe er r { T T v v[i i] ; i in nt t s sz z; p pu ub bl li ic c: B Bu uf ff fe er r() : s sz z(i i) {} / / ... }; B Bu uf ff fe er r<c ch ha ar r,1 12 27 7> c cb bu uf f; B Bu uf ff fe read more..

  • Page - 344

    Section 13.2.4 Type Equivalence 333 because c ch ha ar r and u un ns si ig gn ne ed d c ch ha ar r are different types (§4.3), S St tr ri in ng g<c ch ha ar r> and S St tr ri in ng g<u un ns si ig gn ne ed d c ch ha ar r> are different types. The compiler can evaluate constant expressions (§C.5), so B Bu uf ff fe er r<c ch read more..

  • Page - 345

    334 Templates Chapter 13 usually called the first point of instantiation, or simply the point of instantiation (see §C.13.7). The implementation is allowed to postpone this checking until the program is linked. If we had only a declaration of p pr ri in nt t _ _a al ll l() available in this translation unit, rather than its definition, the implemen- tation might have had read more..

  • Page - 346

    Section 13.3 Function Templates 335 This does not introduce any new overheads. In this example, operator < is used for comparison. However, not every type has a < operator. This limits the use of this version of s so or rt t(), but the limitation is easily avoided (see §13.4). 13.3.1 Function Template Arguments [temp.deduce] Function templates are essential for writing read more..

  • Page - 347

    336 Templates Chapter 13 i im mp pl li ic ci it t _ _c ca as st t<c ch ha ar r,d do ou ub bl le e>(i i) ; / / T is char; U is double i im mp pl li ic ci it t _ _c ca as st t<c ch ha ar r*,i in nt t>(i i) ; / / T is char*; U is int; error: cannot convert int to char* } As with default function arguments (§7.5), only trailing read more..

  • Page - 348

    Section 13.3.2 Function Template Overloading 337 [3] Do overload resolution for this set of functions, plus any ordinary functions as for ordinary functions (§7.4). If a template function argument has been determined by template argu- ment deduction (§13.3.1), that argument cannot also have promotions, standard conversions, or user-defined conversions applied. For s sq qr rt t(2 2) , s sq qr read more..

  • Page - 349

    338 Templates Chapter 13 t te em mp pl la at te e<c cl la as ss s T T> c cl la as ss s B B { /* ... */ }; t te em mp pl la at te e<c cl la as ss s T T> c cl la as ss s D D : p pu ub bl li ic c B B<T T> { /* ... */ }; t te em mp pl la at te e<c cl la as ss s T T> v vo oi id d f f(B B<T read more..

  • Page - 350

    Section 13.4 Using Template Arguments to Specify Policy 339 like to use for a comparison? Two different collating sequences (numerical orderings of the charac- ters) are commonly used for sorting Swedish names. Naturally, neither a general string type nor a general sort algorithm should know about the conventions for sorting names in Sweden. Therefore, any general solution requires read more..

  • Page - 351

    340 Templates Chapter 13 13.4.1 Default Template Parameters [temp.default] Explicitly specifying the comparison criteria for each call is tedious. Fortunately, it is easy to pick a default so that only uncommon comparison criteria have to be explicitly specified. This can be implemented through overloading: t te em mp pl la at te e<c cl la as ss s T T, c cl la as ss s read more..

  • Page - 352

    Section 13.5 Specialization 341 13.5 Specialization [temp.special] By default, a template gives a single definition to be used for every template argument (or combina- tion of template arguments) that a user can think of. This doesn’t always make sense for someone writing a template. I might want to say, ‘‘if the template argument is a pointer, use this implemen- tation; if read more..

  • Page - 353

    342 Templates Chapter 13 The t te em mp pl la at te e<> prefix says that this is a specialization that can be specified without a template parameter. The template arguments for which the specialization is to be used are specified in <> brackets after the name. That is, the < v vo oi id d*> says that this definition is to be used as the imple- read more..

  • Page - 354

    Section 13.5 Specialization 343 to implement all lists of pointers is an example of the general technique of minimizing code bloat by maximizing the amount of shared code. The general template must be declared before any specialization. For example: t te em mp pl la at te e<c cl la as ss s T T> c cl la as ss s L Li is st t<T T*> { /* ... */ }; t read more..

  • Page - 355

    344 Templates Chapter 13 13.5.2 Template Function Specialization [temp.special.fct] Naturally, specialization is also useful for template functions. Consider the Shell sort from §7.7 and §13.3. It compares elements using < and swaps elements using detailed code. A better defini- tion would be: t te em mp pl la at te e<c cl la as ss s T T> b bo oo ol l l le es read more..

  • Page - 356

    Section 13.5.2 Template Function Specialization 345 t te em mp pl la at te e<c cl la as ss s T T> v vo oi id d s sw wa ap p(T T& x x, T T& y y) { T T t t = x x; / / copy x to temporary x x = y y; / / copy y to x y y = t t; / / copy temporary to y } This is rather inefficient when invoked for V Ve ec ct to or rs of read more..

  • Page - 357

    346 Templates Chapter 13 class depend on a template parameter of a derived class, the base itself must be parameterized; V Ve ec c from §3.7.1 is an example of this: t te em mp pl la at te e<c cl la as ss s T T> c cl la as ss s v ve ec ct to or r { /* ... */ }; t te em mp pl la at te e<c cl la as ss s T T> c cl la as ss s V read more..

  • Page - 358

    Section 13.6 Derivation and Templates 347 f fr ri ie en nd d b bo oo ol l o op pe er ra at to or r==(c co on ns st t M Mc co on nt ta ai in ne er r&, c co on ns st t M Mc co on nt ta ai in ne er r&) ; / / compare elements f fr ri ie en nd d b bo oo ol l o op pe er ra at to or r!=(c co on ns st t M Mc co read more..

  • Page - 359

    348 Templates Chapter 13 c cl la as ss s Q Qu ua ad d { / / no conversion to int }; c co om mp pl le ex x<Q Qu ua ad d> c cq q; c co om mp pl le ex x<i in nt t> c ci i = c cq q; / / error: no Quad to int conversion In other words, you can construct a c co om mp pl le ex x<T T1 1> from a c co om mp pl le ex read more..

  • Page - 360

    Section 13.6.3 Inheritance Relationships 349 Given these declarations, people sometimes try to treat a s se et t<C Ci ir rc cl le e*> as a s se et t<S Sh ha ap pe e*>. This is a serious logical error based on a flawed argument: ‘‘A C Ci ir rc cl le e is a S Sh ha ap pe e, so a set of C Ci ir rc cl le es s is also a set of S Sh read more..

  • Page - 361

    350 Templates Chapter 13 v vo oi id d f f(P Pt tr r<C Ci ir rc cl le e> p pc c) { P Pt tr r<S Sh ha ap pe e> p ps s = p pc c; / / should work P Pt tr r<C Ci ir rc cl le e> p pc c2 2 = p ps s; / / should give error } We want to allow the first initialization if and only if S Sh ha ap pe e really is a direct or read more..

  • Page - 362

    Section 13.7 Source Code Organization 351 / / user1.c: # i in nc cl lu ud de e " o ou ut t.c c" / / use out() / / user2.c: # i in nc cl lu ud de e " o ou ut t.c c" / / use out() That is, the definition of o ou ut t() and all declarations it depends on are # i in nc cl lu ud de ed in several different compilation units. It is up read more..

  • Page - 363

    352 Templates Chapter 13 system used, the kind of application you are building, and the external constraints on the way you build systems. Generally, inline functions and other small functions that primarily call other tem- plate functions are candidates for inclusion into every compilation unit in which they are used. On an implementation with average support from the linker for read more..

  • Page - 364

    Section 13.8 Advice 353 [17] Use explicit instantiation to minimize compile time and link time; §C.13.10. [18] Prefer a template over derived classes when run-time efficiency is at a premium; §13.6.1. [19] Prefer derived classes over a template if adding new variants without recompilation is impor- tant; §13.6.1. [20] Prefer a template over derived classes when no common base can read more..

  • Page - 365

    354 Templates Chapter 13 15. ( ∗1.5) Construct an example that demonstrates at least three differences between a function tem- plate and a macro (not counting the differences in definition syntax). 16. ( ∗2) Devise a scheme that ensures that the compiler tests general constraints on the template arguments for every template for which an object is constructed. It is not read more..

  • Page - 366

    _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 14 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Exception Handling Don´t interrupt me while I´m interrupting. – read more..

  • Page - 367

    356 Exception Handling Chapter 14 Case [1], ‘‘terminate the program,’’ is what happens by default when an exception isn’t caught. For most errors, we can and must do better. In particular, a library that doesn’t know about the pur- pose and general strategy of the program in which it is embedded cannot simply e ex xi it t() or a ab bo or rt t(). A library that read more..

  • Page - 368

    Section 14.1 Error Handling 357 message would typically refer to library concepts completely unknown to a user (say, ‘‘bad argu- ment to atan2,’’ caused by bad input to a graphics system). A good library doesn’t ‘‘blabber’’ in this way. Exceptions provide a way for code that detects a problem from which it cannot recover to pass the problem on to some part of the read more..

  • Page - 369

    358 Exception Handling Chapter 14 handling mechanism was designed to be effective in a concurrent program as long as the program- mer (or system) enforces basic concurrency rules, such as properly locking a shared data structure while using it. The C++ exception-handling mechanisms are provided to report and handle errors and excep- tional events. However, the programmer must decide read more..

  • Page - 370

    Section 14.2 Grouping of Exceptions 359 Organizing exceptions into hierarchies can be important for robustness of code. For example, consider how you would handle all exceptions from a library of mathematical functions without such a grouping mechanism. This would have to be done by exhaustively listing the exceptions: v vo oi id d g g() { t tr ry y { / / ... } c ca at read more..

  • Page - 371

    360 Exception Handling Chapter 14 p pu ub bl li ic c: I In nt t _ _o ov ve er rf fl lo ow w(c co on ns st t c ch ha ar r* p p, i in nt t a a, i in nt t b b) { o op p = p p; a a1 1 = a a; a a2 2 = b b; } v vi ir rt tu ua al l v vo oi id d d de eb bu ug g _ _p pr ri in nt t() c co on ns st t { c ce read more..

  • Page - 372

    Section 14.2.2 Composite Exceptions 361 Such a N Ne et tf fi il le e _ _e er rr r can be caught by functions dealing with network exceptions: v vo oi id d f f() { t tr ry y { / / something } c ca at tc ch h(N Ne et tw wo or rk k _ _e er rr r& e e) { / / ... } } and also by functions dealing with file system exceptions: v vo oi id d g read more..

  • Page - 373

    362 Exception Handling Chapter 14 In principle, an exception is copied when it is thrown, so the handler gets hold of a copy of the original exception. In fact, an exception may be copied several times before it is caught. Conse- quently, we cannot throw an exception that cannot be copied. The implementation may apply a wide variety of strategies for storing and transmitting read more..

  • Page - 374

    Section 14.3.2 Catch Every Exception 363 v vo oi id d m m() { t tr ry y { / / something } c ca at tc ch h (...) { / / handle every exception / / cleanup t th hr ro ow w; } } That is, if any exception occurs as the result of executing the main part of m m(), the cleanup action in the handler is invoked. Once the local cleanup is done, the exception that read more..

  • Page - 375

    364 Exception Handling Chapter 14 v vo oi id d g g() { t tr ry y { / / ... } c ca at tc ch h (...) { / / handle every exception (§14.3.2) } c ca at tc ch h ( s st td d: : e ex xc ce ep pt ti io on n& e e) { / / handle any standard library exception (§14.10) } c ca at tc ch h ( s st td d: : b ba ad d _ _c ca as st t) { / / read more..

  • Page - 376

    Section 14.4 Resource Management 365 c ca at tc ch h (...) { f fc cl lo os se e(f f) ; t th hr ro ow w; } f fc cl lo os se e(f f) ; } The code using the file is enclosed in a t tr ry y block that catches every exception, closes the file, and re-throws the exception. The problem with this solution is that it is verbose, tedious, and potentially read more..

  • Page - 377

    366 Exception Handling Chapter 14 The destructor will be called independently of whether the function is exited normally or exited because an exception is thrown. That is, the exception-handling mechanisms enable us to remove the error-handling code from the main algorithm. The resulting code is simpler and less error- prone than its traditional counterpart. The process of searching read more..

  • Page - 378

    Section 14.4.1 Using Constructors and Destructors 367 The most common resource acquired in an ad-hoc manner is memory. For example: c cl la as ss s Y Y { i in nt t* p p; v vo oi id d i in ni it t() ; p pu ub bl li ic c: Y Y(i in nt t s s) { p p = n ne ew w i in nt t[s s] ; i in ni it t() ; } ~ Y Y() { d de el le et te e[] p read more..

  • Page - 379

    368 Exception Handling Chapter 14 t te em mp pl la at te e<c cl la as ss s X X> c cl la as ss s s st td d: : a au ut to o _ _p pt tr r { t te em mp pl la at te e < c cl la as ss s Y Y> s st tr ru uc ct t a au ut to o _ _p pt tr r _ _r re ef f { /* ... */ }; / / helper class X X* p pt tr r; p pu ub read more..

  • Page - 380

    Section 14.4.3 Caveat 369 14.4.3 Caveat [except.caveat] Not all programs need to be resilient against all forms of failure, and not all resources are critical enough to warrant the effort to protect them using ‘‘resource acquisition is initialization,’’ a au ut to o _ _p pt tr r, and c ca at tc ch h(...). For example, for many programs that simply read an input and read more..

  • Page - 381

    370 Exception Handling Chapter 14 had run out of free store. When confronted with such problems, programmers come up with two styles of solutions: Resumption: Ask some caller to fix the problem and carry on. Termination: Abandon the computation and return to some caller. In the former case, a caller must be prepared to help out with resource acquisition problems in unknown read more..

  • Page - 382

    Section 14.4.5 Resource Exhaustion 371 the _ _n ne ew w _ _h ha an nd dl le er r, I say: s se et t _ _n ne ew w _ _h ha an nd dl le er r(&m my y _ _n ne ew w _ _h ha an nd dl le er r) ; If I also want to catch b ba ad d _ _a al ll lo oc c, I might say: v vo oi id d f f() { v vo oi id d(*o ol ld dn nh h)() = s se read more..

  • Page - 383

    372 Exception Handling Chapter 14 [3] Don’t do any initialization in the constructor, and rely on the user to call an initialization function before the first use. [4] Mark the object ‘‘uninitialized’’ and have the first member function called for the object do the real initialization, and that function can then report an error if initialization fails. Exception handling allows read more..

  • Page - 384

    Section 14.4.6.1 Exceptions and Member Initialization 373 14.4.6.1 Exceptions and Member Initialization [except.member] What happens if a member initializer (directly or indirectly) throws an exception? By default, the exception is passed on to whatever invoked the constructor for the member’s class. However, the constructor itself can catch such exceptions by enclosing the complete function read more..

  • Page - 385

    374 Exception Handling Chapter 14 X X: :~ X X() t tr ry y { f f() ; / / might throw } c ca at tc ch h (...) { / / do something } The standard library function u un nc ca au ug gh ht t _ _e ex xc ce ep pt ti io on n() returns t tr ru ue e if an exception has been thrown but hasn’t yet been caught. This allows the programmer to specify read more..

  • Page - 386

    Section 14.5 Exceptions That Are Not Errors 375 T Tr re ee e* f fi in nd d(T Tr re ee e* p p, c co on ns st t s st tr ri in ng g& s s) { t tr ry y { f fn nd d(p p,s s) ; } c ca at tc ch h ( T Tr re ee e* q q) { / / q– >str==s r re et tu ur rn n q q; } r re et tu ur rn n 0 0; } However, such use of exceptions read more..

  • Page - 387

    376 Exception Handling Chapter 14 c ca at tc ch h ( x x2 2) { t th hr ro ow w; } / / re-throw c ca at tc ch h ( x x3 3) { t th hr ro ow w; } / / re-throw c ca at tc ch h (...) { s st td d: : u un ne ex xp pe ec ct te ed d() ; / / unexpected() will not return } The most important advantage is that the function declaration belongs to read more..

  • Page - 388

    Section 14.6.1 Checking Exception Specifications 377 then function in a partially updated state relying on the dynamic (run-time) detection of unexpected exceptions. This is essential for the maintenance of large systems in which major updates are expensive and not all source code is accessible. A virtual function may be overridden only by a function that has an exception-specification read more..

  • Page - 389

    378 Exception Handling Chapter 14 A well-defined subsystem Y will often have all its exceptions derived from a class Y Ye er rr r. For example, given c cl la as ss s S So om me e _ _Y Ye er rr r : p pu ub bl li ic c Y Ye er rr r { /* ... */ }; a function declared v vo oi id d f f() t th hr ro ow w ( X Xe er rr r, Y Ye er rr r, e read more..

  • Page - 390

    Section 14.6.3.1 User Mapping of Exceptions 379 Memory exhaustion is dealt with by the _ _n ne ew w _ _h ha an nd dl le er r determined by s se et t _ _n ne ew w _ _h ha an nd dl le er r(). Similarly, the response to an unexpected exception is determined by an _ _u un ne ex xp pe ec ct te ed d _ _h ha an nd dl le er r set by s st td d: read more..

  • Page - 391

    380 Exception Handling Chapter 14 c cl la as ss s Y Yu un ne ex xp pe ec ct te ed d : p pu ub bl li ic c Y Ye er rr r { p pu ub bl li ic c: N Ne et tw wo or rk k _ _e ex xc ce ep pt ti io on n* p pe e; Y Yu un ne ex xp pe ec ct te ed d(N Ne et tw wo or rk k _ _e ex xc ce ep pt ti io on n* p p) : p pe e(p read more..

  • Page - 392

    Section 14.7 Uncaught Exceptions 381 An _ _u un nc ca au ug gh ht t _ _h ha an nd dl le er r is assumed not to return to its caller. If it tries to, t te er rm mi in na at te e() will call a ab bo or rt t(). Note that a ab bo or rt t() indicates abnormal exit from the program. The function e ex xi it t() can be used to exit a program read more..

  • Page - 393

    382 Exception Handling Chapter 14 Consider a simple function f f() that appears to have nothing to do with exception handling: v vo oi id d g g(i in nt t) ; v vo oi id d f f() { s st tr ri in ng g s s; / / ... g g(1 1) ; g g(2 2) ; } However, g g() may throw an exception, so f f() must contain code ensuring that s s is destroyed cor- rectly in read more..

  • Page - 394

    Section 14.9 Error-Handling Alternatives 383 14.9 Error-Handling Alternatives [except.alternatives] The purpose of the exception-handling mechanisms is to provide a means for one part of a program to inform another part of a program that an ‘‘exceptional circumstance’’ has been detected. The assumption is that the two parts of the program are written independently and that the part of read more..

  • Page - 395

    384 Exception Handling Chapter 14 v vo oi id d c ca al ll lC C() t th hr ro ow w(C C _ _b bl le ew wi it t) { e er rr rn no o = 0 0; c c _ _f fu un nc ct ti io on n() ; i if f ( e er rr rn no o) { / / cleanup, if possible and necessary t th hr ro ow w C C _ _b bl le ew wi it t(e er rr rn no o) ; } } e ex xt te er read more..

  • Page - 396

    Section 14.10 Standard Exceptions 385 _ ________________________________________________________________________ Standard Exceptions (thrown by the standard library) _ ________________________________________________________________________ _ ________________________________________________________________________ Name Thrown by Reference Header _ ________________________________________________________________________ o ou ut t _ _o of f read more..

  • Page - 397

    386 Exception Handling Chapter 14 c ca at tc ch h ( e ex xc ce ep pt ti io on n& e e) { c co ou ut t << " s st ta an nd da ar rd d l li ib br ra ar ry y e ex xc ce ep pt ti io on n " << e e.w wh ha at t() << ´ \ \n n´; / / well, maybe / / ... } c ca at tc ch h (...) { c co ou ut t << read more..

  • Page - 398

    Section 14.11 Advice 387 [8] Throw an exception to indicate failure in a constructor; §14.4.6. [9] Avoid throwing exceptions from copy constructors; §14.4.6.1. [10] Avoid throwing exceptions from destructors; §14.4.7. [11] Have m ma ai in n() catch and report all exceptions; §14.7. [12] Keep ordinary code and error-handling code separate; §14.4.5, §14.5. [13] Be sure that every read more..

  • Page - 399

    388 Exception Handling Chapter 14 c ca al ll l _ _f fr ro om m _ _C C() in §14.9 doesn’t quite handle all cases. 10. ( ∗2) Write a class or template suitable for implementing callbacks. 11. ( ∗2.5) Write a L Lo oc ck k class for some system supporting concurrency. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by read more..

  • Page - 400

    _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 15 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Class Hierarchies Abstraction is selective ignorance. – read more..

  • Page - 401

    390 Class Hierarchies Chapter 15 15.2 Multiple Inheritance [hier.mi] As shown in §2.5.4 and §12.3, a class can have more than one direct base class, that is, more than one class specified after the : in the class declaration. Consider a simulation in which concurrent activities are represented by a class T Ta as sk k and data gathering and display is achieved through a read more..

  • Page - 402

    Section 15.2 Multiple Inheritance 391 c cl la as ss s S Sa at te el ll li it te e : p pu ub bl li ic c T Ta as sk k, p pu ub bl li ic c D Di is sp pl la ay ye ed d { / / ... v vo oi id d p pe en nd di in ng g() ; / / override Task::pending() v vo oi id d d dr ra aw w() ; / / override Displayed::draw() }; This ensures that S read more..

  • Page - 403

    392 Class Hierarchies Chapter 15 c cl la as ss s S Sa at te el ll li it te e : p pu ub bl li ic c T Ta as sk k, p pu ub bl li ic c D Di is sp pl la ay ye ed d { / / ... d de eb bu ug g _ _i in nf fo o* g ge et t _ _d de eb bu ug g() / / override Task::get _debug() and Displayed::get _debug() { d de eb bu ug g _ _i in read more..

  • Page - 404

    Section 15.2.2 Inheritance and Using-Declarations 393 c cl la as ss s D Di is sp pl la ay ye ed d { / / ... v vo oi id d d de eb bu ug g(i in nt t v v) ; / / the higher the ‘v,’ the more debug information is printed }; c cl la as ss s S Sa at te el ll li it te e : p pu ub bl li ic c T Ta as sk k, p pu ub bl li ic c D read more..

  • Page - 405

    394 Class Hierarchies Chapter 15 A using-declaration (§8.2.2) in a class definition must refer to members of a base class. A using-declaration may not be used for a member of a class from outside that class, its derived classes, and their member functions. A using-directive (§8.2.3) may not appear in a class definition and may not be used for a class. A using-declaration cannot be used to gain access read more..

  • Page - 406

    Section 15.2.3 Replicated Base Classes 395 p p->T Ta as sk k: : L Li in nk k: : n ne ex xt t = 0 0; / / ok p p->D Di is sp pl la ay ye ed d: : L Li in nk k: : n ne ex xt t = 0 0; / / ok / / ... } This is exactly the mechanism used to resolve ambiguous references to members (§15.2.1). 15.2.3.1 Overriding [hier.override] A virtual function of read more..

  • Page - 407

    396 Class Hierarchies Chapter 15 v vo oi id d R Ra ad di io o: : w wr ri it te e() { T Tr ra an ns sm mi it tt te er r: : w wr ri it te e() ; R Re ec ce ei iv ve er r: : w wr ri it te e() ; / / write radio-specific information } Casting from a replicated base class to a derived class is discussed in §15.4.2. For a technique for read more..

  • Page - 408

    Section 15.2.4 Virtual Base Classes 397 c cl la as ss s R Ra ad di io o : p pu ub bl li ic c T Tr ra an ns sm mi it tt te er r, p pu ub bl li ic c R Re ec ce ei iv ve er r { p pu ub bl li ic c: v vo oi id d w wr ri it te e() ; / / ... }; Or graphically: S St to or ra ab bl le e R Re ec ce ei iv ve er r T Tr read more..

  • Page - 409

    398 Class Hierarchies Chapter 15 The constructor for a virtual base is called before the constructors for its derived classes. Where needed, the programmer can simulate this scheme by calling a virtual base class function only from the most derived class. For example, assume we have a basic W Wi in nd do ow w class that knows how to draw its contents: c cl la as ss read more..

  • Page - 410

    Section 15.2.4.1 Programming Virtual Bases 399 v vo oi id d W Wi in nd do ow w _ _w wi it th h _ _b bo or rd de er r: : d dr ra aw w() { W Wi in nd do ow w: : d dr ra aw w() ; o ow wn n _ _d dr ra aw w() ; / / display the border } v vo oi id d W Wi in nd do ow w _ _w wi it th h _ _m me en nu u: : d dr ra aw w() { read more..

  • Page - 411

    400 Class Hierarchies Chapter 15 diamond-shaped inheritance occurs (for example, the R Ra ad di io o (§15.2.4) and C Cl lo oc ck k (§15.2.4.1)). A virtual base class, as opposed to an ordinary base class, is needed if the base class cannot be repli- cated. I find that a diamond-shaped inheritance lattice is most manageable if either the virtual base class or the classes read more..

  • Page - 412

    Section 15.2.5 Using Multiple Inheritance 401 I Iv va al l _ _s sl li id de er r I Iv va al l _ _s sl li id de er r P Po op pu up p _ _i iv va al l _ _s sl li id de er r B BB B _ _i iv va al l _ _s sl li id de er r B BB B _ _p po op pu up p _ _i iv va al l _ _s sl li id de er r B BB Bs sl li id de er r .. read more..

  • Page - 413

    402 Class Hierarchies Chapter 15 W Wi in nd do ow w { s se et t _ _c co ol lo or r(), p pr ro om mp pt t() } W Wi in nd do ow w _ _w wi it th h _ _b bo or rd de er r { s se et t _ _c co ol lo or r() } W Wi in nd do ow w _ _w wi it th h _ _m me en nu u { p pr ro om mp pt t() } M My y _ _w wi in nd do ow w read more..

  • Page - 414

    Section 15.3 Access Control 403 t te em mp pl la at te e<c cl la as ss s T T> c cl la as ss s L Li is st t { p pr ri iv va at te e: s st tr ru uc ct t L Li in nk k { T T v va al l; L Li in nk k* n ne ex xt t; }; s st tr ru uc ct t C Ch hu un nk k { e en nu um m { c ch hu un nk k _ _s si iz ze e read more..

  • Page - 415

    404 Class Hierarchies Chapter 15 Nonmember functions (except friends) do not have such access: v vo oi id d w wo ou ul ld d _ _b be e _ _m me ed dd dl le er r(L Li is st t<T T>* p p) { L Li is st t<T T>: : L Li in nk k* q q = 0 0; / / error: List <T>::Link is private / / ... q q = p p->f fr re ee e; / / error: List read more..

  • Page - 416

    Section 15.3.1 Protected Members 405 This prevents subtle errors that would otherwise occur when one derived class corrupts data belonging to other derived classes. 15.3.1.1 Use of Protected Members [hier.protected.use] The simple private/public model of data hiding serves the notion of concrete types (§10.3) well. However, when derived classes are used, there are two kinds of users of read more..

  • Page - 417

    406 Class Hierarchies Chapter 15 The access specifier for a base class controls the access to members of the base class and the conversion of pointers and references from the derived class type to the base class type. Consider a class D D derived from a base class B B: – If B B is a p pr ri iv va at te e base, its public and protected members can be used read more..

  • Page - 418

    Section 15.3.2.1 Multiple Inheritance and Access Control 407 15.3.2.2 Using-Declarations and Access Control [hier.access.using] A using-declaration cannot be used to gain access to additional information. It is simply a mecha- nism for making accessible information more convenient to use. On the other hand, once access is available, it can be granted to other users. For example: c cl read more..

  • Page - 419

    408 Class Hierarchies Chapter 15 v vo oi id d m my y _ _e ev ve en nt t _ _h ha an nd dl le er r(B BB Bw wi in nd do ow w* p pw w) { i if f ( I Iv va al l _ _b bo ox x* p pb b = d dy yn na am mi ic c _ _c ca as st t<I Iv va al l _ _b bo ox x*>(p pw w)) / / does pw point to an Ival _box? p pb b->d do o _ read more..

  • Page - 420

    Section 15.4.1 Dynamic _cast 409 c cl la as ss s B BB B _ _i iv va al l _ _s sl li id de er r : p pu ub bl li ic c I Iv va al l _ _s sl li id de er r, p pr ro ot te ec ct te ed d B BB Bs sl li id de er r { / / ... }; v vo oi id d f f(B BB B _ _i iv va al l _ _s sl li id de er r* p p) { I Iv va al l _ _s read more..

  • Page - 421

    410 Class Hierarchies Chapter 15 . .. .. . v vp pt tr r . .. .. . " "M My y _ _b bo ox x" " b ba as se es s . . " "I Iv va al l _ _s sl li id de er r" " . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . v vt tb bl l: : M My y _ _b bo ox x: : t ty yp pe e _ read more..

  • Page - 422

    Section 15.4.1.1 Dynamic _cast of References 411 Given a pointer result, we must consider the possibility that the result is 0 0; that is, that the pointer doesn’t point to an object. Consequently, the result of a d dy yn na am mi ic c _ _c ca as st t of a pointer should always be explicitly tested. For a pointer p p, d dy yn na am mi ic c _ _c ca as read more..

  • Page - 423

    412 Class Hierarchies Chapter 15 once in a hierarchy, we must be a bit careful when we refer to the object or objects that represent that class. Naturally, we try to keep hierarchies as simple as our application allows (and no simpler). However, once a nontrivial hierarchy has been made we soon need to navigate it to find an appro- priate class to use as an interface. read more..

  • Page - 424

    Section 15.4.2 Navigating Class Hierarchies 413 there is always a unique sub-object of a given cast (or none) when downcasting (that is, towards a derived class; §15.4). The equivalent ambiguity occurs when upcasting (that is, towards a base; §15.4) and such ambiguities are caught at compile time. 15.4.2.1 Static and Dynamic Casts [hier.static.cast] A d dy yn na am mi ic c _ _c ca as read more..

  • Page - 425

    414 Class Hierarchies Chapter 15 v vo oi id d f f(U Us se er rs s* p pu u, c co on ns st t R Re ec ce ei iv ve er r* p pc cr r) { s st ta at ti ic c _ _c ca as st t<s se et t<P Pe er rs so on n>*>(p pu u) ; / / error: access violation d dy yn na am mi ic c _ _c ca as st t<s se et t<P Pe er rs so on read more..

  • Page - 426

    Section 15.4.4 Typeid and Extended Type Information 415 t ty yp pe e _ _i in nf fo o that represents the type of the object denoted by the expression. A t ty yp pe ei id d() is most commonly used to find the type of an object referred to by a reference or a pointer: v vo oi id d f f(S Sh ha ap pe e& r r, S Sh ha ap pe e* p p) { t ty yp read more..

  • Page - 427

    416 Class Hierarchies Chapter 15 15.4.4.1 Extended Type Information [hier.extended] Typically, finding the exact type of an object is simply the first step to acquiring and using more- detailed information about that type. Consider how an implementation or a tool could make information about types available to users at run time. Suppose I have a tool that generates descriptions of read more..

  • Page - 428

    Section 15.4.5 Uses and Misuses of RTTI 417 15.4.5 Uses and Misuses of RTTI [hier.misuse] One should use explicit run-time type information only when necessary. Static (compile-time) checking is safer, implies less overhead, and – where applicable – leads to better-structured pro- grams. For example, RTTI can be used to write thinly disguised switch-statements: / / misuse of read more..

  • Page - 429

    418 Class Hierarchies Chapter 15 c cl la as ss s S Sh hi ip p : p pu ub bl li ic c O Ob bj je ec ct t { /* ... */ }; S Sh hi ip p* f f(S Sh hi ip p* p ps s, C Co on nt ta ai in ne er r* c c) { c c->p pu ut t(p ps s) ; / / ... O Ob bj je ec ct t* p p = c c->g ge et t() ; i if f ( S Sh hi ip p* q q = d read more..

  • Page - 430

    Section 15.5 Pointers to Members 419 Ideally, such intermediate layers of software should not have to know anything about the individual operations such as r re es su um me e() and f fu ul ll l _ _s si iz ze e(). If they did, the intermediate layers would have to be updated each time the set of operations changed. Consequently, such intermediate layers simply transmit read more..

  • Page - 431

    420 Class Hierarchies Chapter 15 This can be represented graphically like this: X X: :: :s st ta ar rt t . . X X: :: :s su us sp pe en nd d v vt tb bl l: : s s .. . . . . . p p .. Because a pointer to a virtual member (s s in this example) is a kind of offset, it does not depend on an object’s location in memory. A pointer to a virtual member read more..

  • Page - 432

    Section 15.5.1 Base and Derived Classes 421 c cl la as ss s t te ex xt t : p pu ub bl li ic c S St td d _ _i in nt te er rf fa ac ce e { p pu ub bl li ic c: v vo oi id d s st ta ar rt t() ; v vo oi id d s su us sp pe en nd d() ; / / ... v vi ir rt tu ua al l v vo oi id d p pr ri in nt t() ; p pr ri iv va read more..

  • Page - 433

    422 Class Hierarchies Chapter 15 v vo oi id d E Em mp pl lo oy ye ee e: : o op pe er ra at to or r d de el le et te e(v vo oi id d* p p, s si iz ze e _ _t t s s) { / / assume ‘p’ points to ‘s’ bytes of memory allocated by Employee::operator new() / / and free that memory for reuse } The use of the hitherto mysterious s si iz ze e _ read more..

  • Page - 434

    Section 15.6 Free Store 423 v vo oi id d f f() { E Em mp pl lo oy ye ee e* p p = n ne ew w M Ma an na ag ge er r; d de el le et te e p p; / / now fine (Employee is polymorphic) } Allocation is done by a (compiler-generated) call: E Em mp pl lo oy ye ee e: : o op pe er ra at to or r n ne ew w(s si iz ze eo of f(M Ma an na read more..

  • Page - 435

    424 Class Hierarchies Chapter 15 15.6.2 “Virtual Constructors” [hier.vctor] After hearing about virtual destructors, the obvious question is, ‘‘Can constructors be virtual?’’ The short answer is no; a slightly longer one is, no, but you can easily get the effect you are looking for. To construct an object, a constructor needs the exact type of the object it is to create. read more..

  • Page - 436

    Section 15.6.2 “Virtual Constructors” 425 This allows a C Co on nd d to be cloned without loss of type information. For example: v vo oi id d u us se er r2 2(C Co on nd d* p pc c, E Ex xp pr r* p pe e) { C Co on nd d* p p2 2 = p pc c->c cl lo on ne e() ; C Co on nd d* p p3 3 = p pe e->c cl lo on ne e() ; / / error / / read more..

  • Page - 437

    426 Class Hierarchies Chapter 15 supplied there. Define a database object class with a plausible set of operations to serve as a common base class for objects stored as sequences of fields in a database; look at a database library to see what operations were supplied there. Define a graphical database object with and without the use of multiple inheritance and discuss the read more..

  • Page - 438

    Part III The Standard Library This part describes the C++ standard library. It presents the design of the library and key techniques used in its implementation. The aim is to provide understanding of how to use the library, to demonstrate generally useful design and programming tech- niques, and to show how to extend the library in the ways in which it was intended to be read more..

  • Page - 439

    428 The Standard Library Part III The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved. read more..

  • Page - 440

    _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 16 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Library Organization and Containers It was new. It was read more..

  • Page - 441

    430 Library Organization and Containers Chapter 16 support facilities that allow a user to provide I/O of a user-defined type in the style of I/O for built-in types. [6] Provides the common foundation for other libraries. In addition, a few facilities – such as random-number generators (§22.7) – are provided by the standard library simply because it is conventional and useful read more..

  • Page - 442

    Section 16.1.1 Design Constraints 431 a comparison function as an argument rather than relying on something fixed, say, the < operator (§7.7). On the other hand, the overhead imposed by a function call for each comparison compro- mises q qs so or rt t() as a building block for further library building. For almost every data type, it is easy to do a comparison without read more..

  • Page - 443

    432 Library Organization and Containers Chapter 16 _ _____________________________________________________ General Utilities _ _____________________________________________________ _ _____________________________________________________ < <u ut ti il li it ty y > > operators and pairs §17.1.4, §17.4.1.2 < <f fu un nc ct ti io on na al l > > function objects §18.4 < <m me em mo read more..

  • Page - 444

    Section 16.1.2 Standard Library Organization 433 _ ___________________________________________________________ Input/Output _ ___________________________________________________________ _ ___________________________________________________________ < <i io os sf fw wd d > > forward declarations of I/O facilities §21.1 < <i io os st tr re ea am m > > standard iostream objects and operations read more..

  • Page - 445

    434 Library Organization and Containers Chapter 16 _ ________________________________________________ Numerics _ ________________________________________________ _ ________________________________________________ < <c co om mp pl le ex x > > complex numbers and operations §22.5 < <v va al la ar rr ra ay y > > numeric vectors and operations §22.4 < <n nu um me er ri ic read more..

  • Page - 446

    Section 16.2 Container Design 435 Container designs typically meet just one or the other of these two design criteria. The con- tainer and algorithms part of the standard library (often called the STL) can be seen as a solution to the problem of simultaneously providing generality and efficiency. The following sections present the strengths and weaknesses of two traditional styles read more..

  • Page - 447

    436 Library Organization and Containers Chapter 16 We can now provide implementations for V Ve ec ct to or rs and L Li is st ts: t te em mp pl la at te e<c cl la as ss s T T> c cl la as ss s V Ve ec ct to or r _ _i it to or r : p pu ub bl li ic c I It to or r<T T> { / / Vector implementation V Ve ec ct to or r<T read more..

  • Page - 448

    Section 16.2.1 Specialized Containers and Iterators 437 + Commonality of use is provided through iterators (rather than through a general container type; §16.2.2). + Different iterators can be defined to serve different needs for the same container. + Containers are by default type safe and homogeneous (that is, all elements in a container are of the same type). A heterogeneous read more..

  • Page - 449

    438 Library Organization and Containers Chapter 16 16.2.2 Based Containers [org.based] One can define an intrusive container without relying on templates or any other way of parameter- izing a type declaration. For example: s st tr ru uc ct t L Li in nk k { L Li in nk k* p pr re e; L Li in nk k* s su uc c; / / ... }; c cl la as ss s L Li is st t { read more..

  • Page - 450

    Section 16.2.2 Based Containers 439 c cl la as ss s L Li is st t : p pu ub bl li ic c C Co on nt ta ai in ne er r { p pu ub bl li ic c: O Ob bj je ec ct t* g ge et t() ; v vo oi id d p pu ut t(O Ob bj je ec ct t*) ; / / ... }; c cl la as ss s V Ve ec ct to or r : p pu ub bl li ic c C Co on nt ta ai in ne read more..

  • Page - 451

    440 Library Organization and Containers Chapter 16 e el ls se e { / / Oops, do something else } } } c ca at tc ch h ( C Co on nt ta ai in ne er r: : B Ba ad d _ _o op p& b ba ad d) { / / Oops, do something else } } This is tedious, so the checking for B Ba ad d _ _o op p will typically be elsewhere. By relying on exceptions caught read more..

  • Page - 452

    Section 16.2.2 Based Containers 441 every container. This greatly eases the provision of universal services such as persistence and object I/O. As before (§16.2.1), + indicates an advantage and - indicates a disadvantage. Compared to the approach using unrelated containers and iterators, the based-object approach unnecessarily pushes complexity onto the user, imposes significant run-time read more..

  • Page - 453

    442 Library Organization and Containers Chapter 16 + To serve different needs for containers, different iterators and other generalized interfaces can be defined in addition to the standard iterators. + Containers are by default type-safe and homogeneous (that is, all elements in a container are of the same type). A heterogeneous container can be provided as a homogeneous container read more..

  • Page - 454

    Section 16.3.1 Types 443 t ty yp pe ed de ef f T T v va al lu ue e _ _t ty yp pe e; / / type of element t ty yp pe ed de ef f A A a al ll lo oc ca at to or r _ _t ty yp pe e; / / type of memory manager t ty yp pe ed de ef f t ty yp pe en na am me e A A: : s si iz ze e _ _t ty yp pe e s si iz ze e _ _t ty read more..

  • Page - 455

    444 Library Organization and Containers Chapter 16 Having to add t ty yp pe en na am me e before the names of member types of a template parameter is a nuisance. However, the compiler isn’t psychic. There is no general way for it to know whether a member of a template argument type is a typename (§C.13.5). As for pointers, prefix * means dereference the iterator read more..

  • Page - 456

    Section 16.3.2 Iterators 445 t te em mp pl la at te e<c cl la as ss s C C> t ty yp pe en na am me e C C: : i it te er ra at to or r f fi in nd d _ _l la as st t(c co on ns st t C C& c c, t ty yp pe en na am me e C C: : v va al lu ue e _ _t ty yp pe e v v) { r re et tu ur rn n f fi in nd d _ _f read more..

  • Page - 457

    446 Library Organization and Containers Chapter 16 r re ef fe er re en nc ce e f fr ro on nt t() ; / / first element c co on ns st t _ _r re ef fe er re en nc ce e f fr ro on nt t() c co on ns st t; r re ef fe er re en nc ce e b ba ac ck k() ; / / last element c co on ns st t _ _r re ef fe er re en nc ce e b ba ac read more..

  • Page - 458

    Section 16.3.3 Element Access 447 They are most useful where these elements are known to exist and in code where these elements are of particular interest. A v ve ec ct to or r used as a s st ta ac ck k (§16.3.5) is an obvious example. Note that f fr ro on nt t() returns a reference to the element to which b be eg gi in n() returns an iterator. I often read more..

  • Page - 459

    448 Library Organization and Containers Chapter 16 c cl la as ss s N Nu um m { / / infinite precision p pu ub bl li ic c: N Nu um m(l lo on ng g) ; / / no default constructor / / ... }; v ve ec ct to or r<N Nu um m> v v1 1(1 10 00 00 0) ; / / error: no default Num v ve ec ct to or r<N Nu um m> v v2 2(1 10 00 00 0,N Nu read more..

  • Page - 460

    Section 16.3.4 Constructors 449 v vo oi id d f f1 1(v ve ec ct to or r<i in nt t>&) ; / / common style v vo oi id d f f2 2(c co on ns st t v ve ec ct to or r<i in nt t>&) ; / / common style v vo oi id d f f3 3(v ve ec ct to or r<i in nt t>) ; / / rare style v vo oi id d h h() { v ve ec ct to or r<i read more..

  • Page - 461

    450 Library Organization and Containers Chapter 16 v vo oi id d f f2 2(v ve ec ct to or r<B Bo oo ok k>& v vh h, l li is st t<B Bo oo ok k>& l lb b) { v ve ec ct to or r<B Bo oo ok k> v vt t(l lb b.b be eg gi in n() , l lb b.e en nd d()) ; v vh h = v vt t; / / ... } However, this can be both ugly and read more..

  • Page - 462

    Section 16.3.5 Stack Operations 451 Each time p pu us sh h _ _b ba ac ck k() is called, the v ve ec ct to or r s s grows by one element and that element is added at the end. So s s[s s.s si iz ze e()-1 1], also known as s s.b ba ac ck k() (§16.3.3), is the element most recently pushed onto the v ve ec ct to or r. Except for the word v ve ec ct read more..

  • Page - 463

    452 Library Organization and Containers Chapter 16 16.3.6 List Operations [org.list] The p pu us sh h _ _b ba ac ck k(), p po op p _ _b ba ac ck k(), and b ba ac ck k() operations (§16.3.5) allow a v ve ec ct to or r to be used effec- tively as a stack. However, it is sometimes also useful to add elements in the middle of a v ve ec ct to or r and read more..

  • Page - 464

    Section 16.3.6 List Operations 453 The e er ra as se e(p p1 1,p p2 2) removes p pe ea ac ch h and p pe ea ar r, yielding: f fr ru ui it t[]: a ap pp pl le e g gr ra ap pe e k ki iw wi if fr ru ui it t s st ta ar rf fr ru ui it t As usual, the sequence specified by the user is from the beginning to one-past-the-end of the sequence read more..

  • Page - 465

    454 Library Organization and Containers Chapter 16 If c ci it tr ru us s is a container c ci it tr ru us s[]: l le em mo on n g gr ra ap pe ef fr ru ui it t o or ra an ng ge e l li im me e we get: f fr ru ui it t[]: a ap pp pl le e c ch he er rr ry y l le em mo on n g gr ra ap pe ef fr ru ui it t o or ra an ng read more..

  • Page - 466

    Section 16.3.7 Addressing Elements 455 c c.e er ra as se e(c c+7 7) ; / / error: adding 7 to a container makes no sense c c.e er ra as se e(c c.b ba ac ck k()) ; / / error: c.back() is a reference, not an iterator c c.e er ra as se e(c c.e en nd d()-2 2) ; / / ok (second to last element) c c.e er ra as se e(c c.r rb be eg gi in n()+2 2) read more..

  • Page - 467

    456 Library Organization and Containers Chapter 16 v vo oi id d H Hi is st to og gr ra am m: : r re ec co or rd d(i in nt t i i) { i if f ( i i<0 0) i i = 0 0; i if f ( c co ou un nt t.s si iz ze e()<=i i) c co ou un nt t.r re es si iz ze e(i i+i i) ; / / make lots of room c co ou un nt t[i i]++; } Using r re es read more..

  • Page - 468

    Section 16.3.8 Size and Capacity 457 In the same way as s si iz ze e() gives the current number of elements, c ca ap pa ac ci it ty y() gives the current number of reserved memory slots; c c.c ca ap pa ac ci it ty y()-c c.s si iz ze e() is the number of elements that can be inserted without causing reallocation. Decreasing the size of a v ve ec ct to read more..

  • Page - 469

    458 Library Organization and Containers Chapter 16 t te em mp pl la at te e < c cl la as ss s T T, c cl la as ss s A A> i in nl li in ne e b bo oo ol l s st td d: : o op pe er ra at to or r<(c co on ns st t v ve ec ct to or r<T T,A A>& x x, c co on ns st t v ve ec ct to or r<T T,A A>& y y) read more..

  • Page - 470

    Section 16.4 Advice 459 16.4 Advice [org.advice] [1] Use standard library facilities to maintain portability; §16.1. [2] Don’t try to redefine standard library facilities; §16.1.2. [3] Don’t believe that the standard library is best for everything. [4] When building a new facility, consider whether it can be presented within the framework offered by the standard library; §16.3. [5] read more..

  • Page - 471

    460 Library Organization and Containers Chapter 16 9. ( ∗2) Complete the C Co on nt ta ai in ne er r, V Ve ec ct to or r, and L Li is st t classes from §16.2.2. 10. ( ∗2.5) Generate 10,000 uniformly distributed random numbers in the range 0 to 1,023 and store them in (a) an standard library v ve ec ct to or r, (b) a V Ve ec ct to or r from read more..

  • Page - 472

    _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 17 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Standard Containers Now is a good time to put your work read more..

  • Page - 473

    462 Standard Containers Chapter 17 (§17.6). By default, a v ve ec ct to or r (§16.3) should be used; it will be implemented to perform well over a wide range of uses. The idea of treating different kinds of containers – and more generally all kinds of information sources – in uniform ways leads to the notion of generic programming (§2.7.2, §3.8). The standard library provides many read more..

  • Page - 474

    Section 17.1.1 Operations Summary 463 Most containers provide efficient operations at the end (back) of their sequence of elements. In addition, lists and deques provide the equivalent operations on the start (front) of their sequences: _ _____________________________________________________ Stack and Queue Operations (§16.3.5, §17.2.2.2) _ _____________________________________________________ _ read more..

  • Page - 475

    464 Standard Containers Chapter 17 _ ____________________________________________________________ Assignments (§16.3.4) _ ____________________________________________________________ _ ____________________________________________________________ o op pe er ra at to or r= =( (x x) ) Copy assignment; elements from container x x. a as ss si ig gn n( (n n, ,x x) ) Assign n n copies of x x (not for read more..

  • Page - 476

    Section 17.1.2 Container Summary 465 Other entries are measures of the efficiency of the operations. A c co on ns st t entry means the operation takes an amount of time that does not depend on the number of elements in the container. Another conventional notation for constant time is O O(1 1). An O O(n n) entry means the entry takes time pro- portional to the number read more..

  • Page - 477

    466 Standard Containers Chapter 17 A m ma ap p is most likely implemented as a (balanced) tree of nodes pointing to (key,value) pairs: r re ep p ... m ma ap p: node node (key,value) pairs: A s st tr ri in ng g might be implemented as outlined in §11.12 or maybe as a sequence of arrays holding a few characters each: r re ep p s st tr ri in ng g: segment descriptors string read more..

  • Page - 478

    Section 17.1.4 Element Requirements 467 Some violations of the rules for standard containers can be detected by a compiler, but others cannot and might then cause unexpected behavior. For example, a copy operation that throws an exception might leave a partially copied element behind. It could even leave the container itself in a state that could cause trouble later. Such copy read more..

  • Page - 479

    468 Standard Containers Chapter 17 f fr ru ui it t: a ap pp pl le e p pe ea ar r A Ap pp pl le e P Pe ea ar r l le em mo on n Sorting using s so or rt t(f fr ru ui it t.b be eg gi in n() , f fr ru ui it t.e en nd d() , N No oc ca as se e()) would yield: f fr ru ui it t: A Ap pp pl le e a ap pp pl le e l le em read more..

  • Page - 480

    Section 17.1.4.2 Other Relational Operators 469 t te em mp pl la at te e<c cl la as ss s T T> b bo oo ol l r re el l _ _o op ps s: : o op pe er ra at to or r!=(c co on ns st t T T& x x, c co on ns st t T T& y y) { r re et tu ur rn n !( x x==y y) ; } t te em mp pl la at te e<c cl la as ss s T T> read more..

  • Page - 481

    470 Standard Containers Chapter 17 17.2.2 List [cont.list] A l li is st t is a sequence optimized for insertion and deletion of elements. Compared to v ve ec ct to or r (and d de eq qu ue e; §17.2.3), subscripting would be painfully slow, so subscripting is not provided for l li is st t. Consequently, l li is st t provides bidirectional iterators (§19.2.1) rather than random-access read more..

  • Page - 482

    Section 17.2.2.1 Splice, Sort, and Merge 471 we can splice the o or ra an ng ge e from c ci it tr ru us s into f fr ru ui it t like this: l li is st t<s st tr ri in ng g>: : i it te er ra at to or r p p = f fi in nd d _ _i if f(f fr ru ui it t.b be eg gi in n() , f fr ru ui it t.e en nd d() , i in ni it ti ia read more..

  • Page - 483

    472 Standard Containers Chapter 17 f f1 1.s so or rt t() ; f f2 2.s so or rt t() ; f f1 1.m me er rg ge e(f f2 2) ; This yields: f f1 1: a ap pp pl le e g gr ra ap pe ef fr ru ui it t l le em mo on n l li im me e o or ra an ng ge e p pe ea ar r q qu ui in nc ce e f f2 2: < e em mp pt ty y> If one of the read more..

  • Page - 484

    Section 17.2.2.3 Other Operations 473 t te em mp pl la at te e < c cl la as ss s T T, c cl la as ss s A A = a al ll lo oc ca at to or r<T T> > c cl la as ss s l li is st t { p pu ub bl li ic c: / / ... v vo oi id d r re em mo ov ve e(c co on ns st t T T& v va al l) ; t te em mp pl la at te e read more..

  • Page - 485

    474 Standard Containers Chapter 17 duplicates we want to remove. For example, we might define a binary predicate (§18.4.2) i in ni it ti ia al l2 2(x x) to compare s st tr ri in ng gs that have the initial x x but yield f fa al ls se e for every s st tr ri in ng g that doesn’t. Given: p pe ea ar r p pe ea ar r a ap pp pl le e a ap pp read more..

  • Page - 486

    Section 17.3 Sequence Adapters 475 17.3 Sequence Adapters [cont.adapters] The v ve ec ct to or r, l li is st t, and d de eq qu ue e sequences cannot be built from each other without loss of efficiency. On the other hand, s st ta ac ck ks and q qu ue eu ue es can be elegantly and efficiently implemented using those three basic sequences. Therefore, s st ta read more..

  • Page - 487

    476 Standard Containers Chapter 17 v vo oi id d p pr ri in nt t _ _b ba ac ck kw wa ar rd ds s(v ve ec ct to or r<i in nt t>& v v) { s st ta ac ck k<i in nt t> s st ta at te e(v v) ; / / initialize state from v w wh hi il le e ( s st ta at te e.s si iz ze e()) { c co ou ut t << s st ta at te e.t to read more..

  • Page - 488

    Section 17.3.2 Queue 477 t te em mp pl la at te e < c cl la as ss s T T, c cl la as ss s C C = d de eq qu ue e<T T> > c cl la as ss s s st td d: : q qu ue eu ue e { p pr ro ot te ec ct te ed d: C C c c; p pu ub bl li ic c: t ty yp pe ed de ef f t ty yp pe en na am me e C C: : v va al lu ue read more..

  • Page - 489

    478 Standard Containers Chapter 17 m m = q q.f fr ro on nt t() ; q q.p po op p() ; } m m.s se er rv vi ic ce e() ; / / call function to serve request } } There is no standard definition of concurrency or locking in C++ or in the world in general. Have a look to see what your system has to offer and how to access it from C++ (§17.8[8]). 17.3.3 read more..

  • Page - 490

    Section 17.3.3 Priority Queue 479 v vo oi id d s se er rv ve er r(p pr ri io or ri it ty y _ _q qu ue eu ue e<M Me es ss sa ag ge e>& q q, L Lo oc ck k& l lc ck k) { w wh hi il le e(!q q.e em mp pt ty y()) { M Me es ss sa ag ge e m m; { L Lo oc ck kP Pt tr r h h(l lc ck k) ; / / hold lock only while read more..

  • Page - 491

    480 Standard Containers Chapter 17 17.4 Associative Containers [cont.assoc] An associative array is one of the most useful general, user-defined types. In fact, it is often a built-in type in languages primarily concerned with text processing and symbolic processing. An associative array, often called a map and sometimes called a dictionary, keeps pairs of values. Given one value, read more..

  • Page - 492

    Section 17.4.1.1 Types 481 t ty yp pe ed de ef f implementation _defined1 i it te er ra at to or r; t ty yp pe ed de ef f implementation _defined2 c co on ns st t _ _i it te er ra at to or r; t ty yp pe ed de ef f t ty yp pe en na am me e A A: : s si iz ze e _ _t ty yp pe e s si iz ze e _ _t ty yp pe e; t ty yp pe ed read more..

  • Page - 493

    482 Standard Containers Chapter 17 We refer to the first element of any p pa ai ir r as f fi ir rs st t and the second as s se ec co on nd d independently of what types they actually are: t te em mp pl la at te e < c cl la as ss s T T1 1, c cl la as ss s T T2 2> s st tr ru uc ct t s st td d: : p pa ai ir r { t ty yp read more..

  • Page - 494

    Section 17.4.1.3 Subscripting 483 The subscript operator performs a lookup on the key given as an index and returns the correspond- ing value. If the key isn’t found, an element with the key and the default value of the m ma ap pp pe ed d _ _t ty yp pe e is inserted into the m ma ap p. For example: v vo oi id d f f() { m ma ap p<s st tr ri in read more..

  • Page - 495

    484 Standard Containers Chapter 17 h ha am mm me er r 9 9 n na ai il l 1 13 35 50 0 s sa aw w 7 7 ---------------- t to ot ta al l 1 13 36 66 6 Note that the items are printed in lexical order (§17.4.1, §17.4.1.5). A subscripting operation must find the key in the m ma ap p. This, of course, is not as cheap as sub- scripting an array with an read more..

  • Page - 496

    Section 17.4.1.5 Comparisons 485 template parameter or as a constructor argument (see §17.3.3). The comparison given is a compari- son of keys, but the v va al lu ue e _ _t ty yp pe e of a m ma ap p is a (key,value) pair. Consequently, v va al lu ue e _ _c co om mp p() is provided to compare such pairs using the key comparison function: t te em mp pl read more..

  • Page - 497

    486 Standard Containers Chapter 17 t te em mp pl la at te e < c cl la as ss s K Ke ey y, c cl la as ss s T T, c cl la as ss s C Cm mp p = l le es ss s<K Ke ey y>, c cl la as ss s A A = a al ll lo oc ca at to or r< p pa ai ir r<c co on ns st t K Ke ey y,T T> > > c cl la as ss s m ma ap p read more..

  • Page - 498

    Section 17.4.1.6 Map Operations 487 f fo or r ( m mu ul lt ti im ma ap p<s st tr ri in ng g,i in nt t>: : i it te er ra at to or r p p = l lb b; p p!=u ub b; ++ p p) { / / ... } } Finding the upper bound and lower bound by two separate operations is neither elegant nor effi- cient. Consequently, the operation e eq qu ua al l _ _r ra read more..

  • Page - 499

    488 Standard Containers Chapter 17 unique keys, insertion takes place only if there is not already an element in the m m with that key. The return value of m m.i in ns se er rt t(v va al l) is a p pa ai ir r<i it te er ra at to or r,b bo oo ol l>. The b bo oo ol l is t tr ru ue e if v va al l was actually inserted. The iterator refers read more..

  • Page - 500

    Section 17.4.1.7 List Operations 489 The integer returned is the number of erased elements. In particular, c co ou un nt t is 0 0 if there was no ele- ment with the key " R Ra at tb be er rt t" to erase. For a m mu ul lt ti im ma ap p or m mu ul lt ti is se et t, the value can be larger than 1 1. Alternatively, one can erase an read more..

  • Page - 501

    490 Standard Containers Chapter 17 17.4.2 Multimap [cont.multimap] A m mu ul lt ti im ma ap p is like a m ma ap p, except that it allows duplicate keys: t te em mp pl la at te e < c cl la as ss s K Ke ey y, c cl la as ss s T T, c cl la as ss s C Cm mp p = l le es ss s<K Ke ey y>, c cl la as ss s A A = a al ll lo read more..

  • Page - 502

    Section 17.4.3 Set 491 17.4.3 Set [cont.set] A s se et t can be seen as a m ma ap p (§17.4.1), where the values are irrelevant, so we keep track of only the keys. This leads to only minor changes to the user interface: t te em mp pl la at te e < c cl la as ss s K Ke ey y, c cl la as ss s C Cm mp p = l le es ss s<K Ke ey y>, c cl la as ss s read more..

  • Page - 503

    492 Standard Containers Chapter 17 17.5.2 Valarray [cont.valarray] A v va al la ar rr ra ay y (§22.4) is a vector for optimized numeric computation. Consequently, a v va al la ar rr ra ay y doesn’t attempt to be a general container. A v va al la ar rr ra ay y provides many useful numeric operations. However, of the standard container operations (§17.1.1), it offers only s si read more..

  • Page - 504

    Section 17.5.3 Bitset 493 1 1 1 1 0 1 1 1 0 1 9 8 7 6 5 4 3 2 1 0 bitset <10>: position: 17.5.3.1 Constructors [cont.bitset.ctor] A b bi it ts se et t can be constructed with default values, from the bits in an u un ns si ig gn ne ed d l lo on ng g i in nt t, or from a s st tr ri in ng g: t te em mp pl la at te e<s si iz ze e _ read more..

  • Page - 505

    494 Standard Containers Chapter 17 17.5.3.2 Bit Manipulation Operations [cont.bitset.oper] A b bi it ts se et t provides the operators for accessing individual bits and for manipulating all bits in the set: t te em mp pl la at te e<s si iz ze e _ _t t N N> c cl la as ss s s st td d: : b bi it ts se et t { p pu ub bl li ic c: / / ... / / read more..

  • Page - 506

    Section 17.5.3.3 Other Operations 495 t te em mp pl la at te e<s si iz ze e _ _t t N N> c cl la as ss s b bi it ts se et t { p pu ub bl li ic c: / / ... u un ns si ig gn ne ed d l lo on ng g t to o _ _u ul lo on ng g() c co on ns st t; t te em mp pl la at te e < c cl la as ss s C Ch h, c cl la as read more..

  • Page - 507

    496 Standard Containers Chapter 17 v vo oi id d b bi in na ar ry y(i in nt t i i) { b bi it ts se et t<8 8*s si iz ze eo of f(i in nt t)> b b = i i; / / assume 8-bit byte (see also §22.2) c co ou ut t << b b << ´ \ \n n´; } This prints the bits represented as 1 1s and 0 0s left-to-right, with the most significant bit read more..

  • Page - 508

    Section 17.5.4 Built-In Arrays 497 f f(a a,a a.s si iz ze e()) ; / / C-style use c c _ _a ar rr ra ay y<i in nt t,1 10 0>: : i it te er ra at to or r p p = f fi in nd d(a a.b be eg gi in n() , a a.e en nd d() , 7 77 77 7) ; / / C++/STL style use / / ... } 17.6 Defining a New Container [cont.hash] The standard containers provide a read more..

  • Page - 509

    498 Standard Containers Chapter 17 Thus, a first approximation of a h ha as sh h _ _m ma ap p looks like this: t te em mp pl la at te e<c cl la as ss s K Ke ey y, c cl la as ss s T T, c cl la as ss s H H = H Ha as sh h<K Ke ey y>, c cl la as ss s E EQ Q = e eq qu ua al l _ _t to o<K Ke ey y>, c cl la as read more..

  • Page - 510

    Section 17.6.2 Representation and Construction 499 key val e next ... key val e next Expressed as declarations, it looks like this: t te em mp pl la at te e<c cl la as ss s K Ke ey y, c cl la as ss s T T, c cl la as ss s H H = H Ha as sh h<K Ke ey y>, c cl la as ss s E EQ Q = e eq qu ua al l _ _t to o<K Ke ey y>, c cl read more..

  • Page - 511

    500 Standard Containers Chapter 17 p pr ri iv va at te e: f fl lo oa at t m ma ax x _ _l lo oa ad d; / / keep v.size() <=b.size()*max_load f fl lo oa at t g gr ro ow w; / / when necessary, resize(bucket _count()*grow) s si iz ze e _ _t ty yp pe e n no o _ _o of f _ _e er ra as se ed d; / / number of entries in v occupied by erased read more..

  • Page - 512

    Section 17.6.2.1 Lookup 501 / / not found: i if f ( b b.s si iz ze e()*m ma ax x _ _l lo oa ad d < v v.s si iz ze e()) { / / if ‘‘too full’’ r re es si iz ze e(b b.s si iz ze e()*g gr ro ow w) ; / / grow r re et tu ur rn n o op pe er ra at to or r[](k k) ; / / rehash } v v.p pu us sh h _ _b ba ac ck k(E En nt read more..

  • Page - 513

    502 Standard Containers Chapter 17 / / ... }; The r re es si iz ze e() operation is essential, reasonably simple, and potentially expensive: t te em mp pl la at te e<c cl la as ss s K Ke ey y, c cl la as ss s T T, c cl la as ss s H H = H Ha as sh h<K Ke ey y>, c cl la as ss s E EQ Q = e eq qu ua al l _ _t to o<K Ke read more..

  • Page - 514

    Section 17.6.2.3 Hashing 503 A good hash function takes a key and returns an integer so that different keys yield different inte- gers with high probability. Choosing a good hash function is an art. However, exclusive-or’ing the bits of the key’s representation into an integer is often acceptable: t te em mp pl la at te e < c cl la as ss s T T> s si iz read more..

  • Page - 515

    504 Standard Containers Chapter 17 17.6.3 Other Hashed Associative Containers [cont.hash.other] For consistency and completeness, the h ha as sh h _ _m ma ap p should have matching h ha as sh h _ _s se et t, h ha as sh h _ _m mu ul lt ti im ma ap p, and h ha as sh h _ _m mu ul lt ti is se et t. Their definitions are obvious from those of h ha as read more..

  • Page - 516

    Section 17.8 Exercises 505 3. ( ∗2) Write a program that lists the distinct words in a file in alphabetical order. Make two ver- sions: one in which a word is simply a whitespace-separated sequence of characters and one in which a word is a sequence of letters separated by any sequence of non-letters. 4. ( ∗2.5) Implement a simple solitaire card game. 5. ( ∗1.5) read more..

  • Page - 517

    506 Standard Containers Chapter 17 a h ha as sh h _ _m ma ap p that needed to use minimal lookup time. In each case, consider what operations you might omit so as to get closer to the ideal (no space overhead and no lookup overhead, respectively). Hint: There is an enormous literature on hash tables. 24. ( ∗2) Devise a strategy for dealing with overflow in h ha read more..

  • Page - 518

    _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 18 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Algorithms and Function Objects Form is liberating. – read more..

  • Page - 519

    508 Algorithms and Function Objects Chapter 18 18.2 Overview of Standard Library Algorithms [algo.summary] At first glimpse, the standard library algorithms can appear overwhelming. However, there are just 60 of them. I have seen classes with more member functions. Furthermore, many algorithms share a common basic behavior and a common interface style that eases understanding. As with read more..

  • Page - 520

    Section 18.2 Overview of Standard Library Algorithms 509 Nonmodifying sequence operations are used to extract information from a sequence or to find the positions of elements in a sequence: _ __________________________________________________________________ Nonmodifying Sequence Operations (§18.5) <algorithm> _ __________________________________________________________________ _ read more..

  • Page - 521

    510 Algorithms and Function Objects Chapter 18 _ _____________________________________________________________________ Modifying Sequence Operations (continued) (§18.6) <algorithm> _ _____________________________________________________________________ _ _____________________________________________________________________ r re em mo ov ve e _ _c co op py y( () ) Copy a sequence removing elements with a given read more..

  • Page - 522

    Section 18.2 Overview of Standard Library Algorithms 511 _ ____________________________________________________________________ Set Algorithms (§18.7.5) <algorithm> _ ____________________________________________________________________ _ ____________________________________________________________________ i in nc cl lu ud de es s( () ) True if a sequence is a subsequence of another. s se et t _ _u un ni io read more..

  • Page - 523

    512 Algorithms and Function Objects Chapter 18 18.3 Sequences and Containers [algo.seq] It is a good general principle that the most common use of something should also be the shortest, the easiest to express, and the safest. The standard library violates this principle in the name of generality. For a standard library, generality is essential. For example, we can find the first read more..

  • Page - 524

    Section 18.3.1 Input Sequences 513 easily detected by a compiler. The second is hard to spot in real code even for an experienced pro- grammer. Cutting down on the number of explicit iterators used alleviates this problem. Here, I outline an approach to dealing with this problem by making the notion of an input sequence explicit. However, to keep the discussion of standard read more..

  • Page - 525

    514 Algorithms and Function Objects Chapter 18 The notion of an output sequence is also useful. However, it is less simple and less immedi- ately useful than the notion of an input sequence (§18.13[7]; see also §19.2.4). 18.4 Function Objects [algo.fct] Many algorithms operate on sequences using iterators and values only. For example, we can f fi in nd d() the first element with read more..

  • Page - 526

    Section 18.4 Function Objects 515 v vo oi id d f f(l li is st t<d do ou ub bl le e>& l ld d) { S Su um m<d do ou ub bl le e> s s; s s = f fo or r _ _e ea ac ch h(l ld d.b be eg gi in n() , l ld d.e en nd d() , s s) ; / / invoke s() for each element of ld c co ou ut t << " t th he e s su um m i is read more..

  • Page - 527

    516 Algorithms and Function Objects Chapter 18 Unary and binary predicates are often useful in combination with algorithms. For example, we can compare two sequences, looking for the first element of one that is not less than its corresponding element in the other: v vo oi id d f f(v ve ec ct to or r<i in nt t>& v vi i, l li is st t<i in nt read more..

  • Page - 528

    Section 18.4.2.1 Overview of Predicates 517 c cl la as ss s P Pe er rs so on n { /* ... */ }; s st tr ru uc ct t C Cl lu ub b { s st tr ri in ng g n na am me e; l li is st t<P Pe er rs so on n*> m me em mb be er rs s; l li is st t<P Pe er rs so on n*> o of ff fi ic ce er rs s; / / ... C Cl lu ub b(c co read more..

  • Page - 529

    518 Algorithms and Function Objects Chapter 18 v vo oi id d d di is sc co ou un nt t(v ve ec ct to or r<d do ou ub bl le e>& a a, v ve ec ct to or r<d do ou ub bl le e>& b b, v ve ec ct to or r<d do ou ub bl le e>& r re es s) { t tr ra an ns sf fo or rm m(a a.b be eg gi in n() , a a.e en nd d() read more..

  • Page - 530

    Section 18.4.4.1 Binders 519 18.4.4.1 Binders [algo.binder] Binary predicates such as l le es ss s (§18.4.2) are useful and flexible. However, we soon discover that the most useful kind of predicate is one that compares a fixed argument repeatedly against a con- tainer element. The l le es ss s _ _t th ha an n _ _7 7() function (§18.4) is a typical example. The l le es ss read more..

  • Page - 531

    520 Algorithms and Function Objects Chapter 18 v vo oi id d f f(l li is st t<i in nt t>& c c) { l li is st t<i in nt t>: : c co on ns st t _ _i it te er ra at to or r p p = f fi in nd d _ _i if f(c c.b be eg gi in n() , c c.e en nd d() , b bi in nd d2 2n nd d(l le es ss s<i in nt t>() , 7 7)) ; / / read more..

  • Page - 532

    Section 18.4.4.2 Member Function Adapters 521 t te em mp pl la at te e<c cl la as ss s R R, c cl la as ss s T T> c cl la as ss s m me em m _ _f fu un n _ _t t : p pu ub bl li ic c u un na ar ry y _ _f fu un nc ct ti io on n<T T*,R R> { R R ( T T: :* p pm mf f)() ; p pu ub bl li ic c: e ex xp pl li ic read more..

  • Page - 533

    522 Algorithms and Function Objects Chapter 18 closely follows that of the member function adapters (§18.4.4.2). Again, a pair of functions and a pair of classes are used: t te em mp pl la at te e < c cl la as ss s A A, c cl la as ss s R R> p po oi in nt te er r _ _t to o _ _u un na ar ry y _ _f fu un nc ct ti io on n<A A,R read more..

  • Page - 534

    Section 18.4.4.4 Negaters 523 t te em mp pl la at te e<c cl la as ss s P Pr re ed d> u un na ar ry y _ _n ne eg ga at te e<P Pr re ed d> n no ot t1 1(c co on ns st t P Pr re ed d& p p) ; / / negate unary t te em mp pl la at te e<c cl la as ss s P Pr re ed d> b bi in na ar ry y _ _n ne eg ga at read more..

  • Page - 535

    524 Algorithms and Function Objects Chapter 18 algorithm in the sense that it does nothing but eliminate an explicit loop. It simply calls its operator argument for a sequence: t te em mp pl la at te e<c cl la as ss s I In n, c cl la as ss s O Op p> O Op p f fo or r _ _e ea ac ch h(I In n f fi ir rs st t, I In n l la as st t, O read more..

  • Page - 536

    Section 18.5.2 The Find Family 525 18.5.2 The Find Family [algo.find] The f fi in nd d() algorithms look through a sequence or a pair of sequences to find a value or a match on a predicate. The simple versions of f fi in nd d() look for a value or for a match with a predicate: t te em mp pl la at te e<c cl la as ss s I In n, c cl la as ss s read more..

  • Page - 537

    526 Algorithms and Function Objects Chapter 18 v vo oi id d f f(v ve ec ct to or r<s st tr ri in ng g>& t te ex xt t) { v ve ec ct to or r<s st tr ri in ng g>: : i it te er ra at to or r p p = a ad dj ja ac ce en nt t _ _f fi in nd d(t te ex xt t.b be eg gi in n() , t te ex xt t.e en nd d() ," t th read more..

  • Page - 538

    Section 18.5.4 Equal and Mismatch 527 18.5.4 Equal and Mismatch [algo.equal] The e eq qu ua al l() and m mi is sm ma at tc ch h() algorithms compare two sequences: t te em mp pl la at te e<c cl la as ss s I In n, c cl la as ss s I In n2 2> b bo oo ol l e eq qu ua al l(I In n f fi ir rs st t, I In n l la as st t, I In read more..

  • Page - 539

    528 Algorithms and Function Objects Chapter 18 18.5.5 Search [algo.search] The s se ea ar rc ch h(), s se ea ar rc ch h _ _n n(), and f fi in nd d _ _e en nd d() algorithms find one sequence as a subsequence in another: t te em mp pl la at te e<c cl la as ss s F Fo or r, c cl la as ss s F Fo or r2 2> F Fo or r s se ea ar rc ch read more..

  • Page - 540

    Section 18.6 Modifying Sequence Algorithms 529 18.6 Modifying Sequence Algorithms [algo.modifying] If you want to change a sequence, you can explicitly iterate through it. You can then modify val- ues. Wherever possible, however, we prefer to avoid this kind of programming in favor of simpler and more systematic styles of programming. The alternative is algorithms that traverse read more..

  • Page - 541

    530 Algorithms and Function Objects Chapter 18 v vo oi id d f f(v ve ec ct to or r<c ch ha ar r>& v vs s) { v ve ec ct to or r<c ch ha ar r> v v; c co op py y(v vs s.b be eg gi in n() , v vs s.e en nd d() , v v.b be eg gi in n()) ; / / might overwrite end of v c co op py y(v vs s.b be eg gi in n() , v vs s.e read more..

  • Page - 542

    Section 18.6.2 Transform 531 t te em mp pl la at te e<c cl la as ss s I In n, c cl la as ss s O Ou ut t, c cl la as ss s O Op p> O Ou ut t t tr ra an ns sf fo or rm m(I In n f fi ir rs st t, I In n l la as st t, O Ou ut t r re es s, O Op p o op p) { w wh hi il le e ( f fi ir rs st t != l la as read more..

  • Page - 543

    532 Algorithms and Function Objects Chapter 18 The t tr ra an ns sf fo or rm m() algorithm that takes two sequences allows people to combine information from two sources. For example, an animation may have a routine that updates the position of a list of shapes by applying a translation: S Sh ha ap pe e* m mo ov ve e _ _s sh ha ap pe e(S Sh ha ap pe e* read more..

  • Page - 544

    Section 18.6.3 Unique 533 The u un ni iq qu ue e() algorithm eliminates adjacent duplicates from a sequence, u un ni iq qu ue e _ _c co op py y() makes a copy without duplicates. For example: v vo oi id d f f(l li is st t<s st tr ri in ng g>& l ls s, v ve ec ct to or r<s st tr ri in ng g>& v vs s) { l ls s.s so or rt read more..

  • Page - 545

    534 Algorithms and Function Objects Chapter 18 To eliminate duplicates from a container, we must explicitly shrink it: t te em mp pl la at te e<c cl la as ss s C C> v vo oi id d e el li im mi in na at te e _ _d du up pl li ic ca at te es s(C C& c c) { s so or rt t(c c.b be eg gi in n() , c c.e en nd d()) ; / / sort t ty read more..

  • Page - 546

    Section 18.6.3.1 Sorting Criteria 535 v vo oi id d e ex xt tr ra ac ct t _ _a an nd d _ _p pr ri in nt t(c co on ns st t l li is st t<C Cl lu ub b>& l lc c) { l li is st t<P Pe er rs so on n*> o of ff f; e ex xt tr ra ac ct t(l lc c,o of ff f) ; s so or rt t(o of ff f.b be eg gi in n() , o of ff f.e read more..

  • Page - 547

    536 Algorithms and Function Objects Chapter 18 t te em mp pl la at te e<c cl la as ss s I In n, c cl la as ss s O Ou ut t, c cl la as ss s P Pr re ed d, c cl la as ss s T T> O Ou ut t r re ep pl la ac ce e _ _c co op py y _ _i if f(I In n f fi ir rs st t, I In n l la as st t, O Ou ut t r re es s, P read more..

  • Page - 548

    Section 18.6.6 Fill and Generate 537 18.6.6 Fill and Generate [algo.fill] The f fi il ll l() and g ge en ne er ra at te e() algorithms exist to systematically assign values to sequences: t te em mp pl la at te e<c cl la as ss s F Fo or r, c cl la as ss s T T> v vo oi id d f fi il ll l(F Fo or r f fi ir rs st t, F Fo or r l read more..

  • Page - 549

    538 Algorithms and Function Objects Chapter 18 position f fi ir rs st t+i i moves to position f fi ir rs st t+(i i+(l la as st t-m mi id dd dl le e))%(l la as st t-f fi ir rs st t). The % (modulo) is what makes the rotation cyclic rather than simply a shift to the left. For example: v vo oi id d f f() { s st tr ri in ng g v v[] = { " read more..

  • Page - 550

    Section 18.7 Sorted Sequences 539 18.7 Sorted Sequences [algo.sorted] Once we have collected some data, we often want to sort it. Once the sequence is sorted, our options for manipulating the data in a convenient manner increase significantly. To sort a sequence, we need a way of comparing elements. This is done using a binary predi- cate (§18.4.2). The default comparison is read more..

  • Page - 551

    540 Algorithms and Function Objects Chapter 18 v vo oi id d f f(c co on ns st t v ve ec ct to or r<B Bo oo ok k>& s sa al le es s) / / find the top ten books { v ve ec ct to or r<B Bo oo ok k> b be es st ts se el ll le er rs s(1 10 0) ; p pa ar rt ti ia al l _ _s so or rt t _ _c co op py y(s sa al le es read more..

  • Page - 552

    Section 18.7.2 Binary Search 541 t te em mp pl la at te e<c cl la as ss s F Fo or r, c cl la as ss s T T> F Fo or r u up pp pe er r _ _b bo ou un nd d(F Fo or r f fi ir rs st t, F Fo or r l la as st t, c co on ns st t T T& v va al l) ; t te em mp pl la at te e<c cl la as ss s F Fo or r, c cl read more..

  • Page - 553

    542 Algorithms and Function Objects Chapter 18 18.7.4 Partitions [algo.partition] To partition a sequence is to place every element that satisfies a predicate before every element that doesn’t. The standard library provides a s st ta ab bl le e _ _p pa ar rt ti it ti io on n(), which maintains relative order among the elements that do and do not satisfy the predicate. read more..

  • Page - 554

    Section 18.7.5 Set Operations on Sequences 543 not its second, input sequence. The s se et t _ _s sy ym mm me et tr ri ic c _ _d di if ff fe er re en nc ce e() algorithm produces a sequence of elements that are members of either, but not of both, of its input sequences: t te em mp pl la at te e<c cl la as ss s I In n, c cl la as ss s I read more..

  • Page - 555

    544 Algorithms and Function Objects Chapter 18 p pu us sh h _ _h he ea ap p() operations. Conversely, p po op p _ _h he ea ap p(f fi ir rs st t,l la as st t) removes the first element of the heap by swapping it with the last element (*(l la as st t-1 1)) and making [ f fi ir rs st t,l la as st t-1 1[ into a heap. 18.9 Min and Max [algo.min] read more..

  • Page - 556

    Section 18.9 Min and Max 545 c ch ha ar r v v1 1[] = " y ye es s"; c ch ha ar r v v2 2[] = " n no o"; s st tr ri in ng g s s1 1 = " Y Ye es s"; s st tr ri in ng g s s2 2 = " N No o"; v vo oi id d f f() { b bo oo ol l b b1 1 = l le ex xi ic co og gr ra ap ph hi ic ca al l _ _c read more..

  • Page - 557

    546 Algorithms and Function Objects Chapter 18 18.11 C-Style Algorithms [algo.c] From the C standard library, the C++ standard library inherited a few algorithms dealing with C- style strings (§20.4.1), plus a quicksort and a binary search, both limited to arrays. The q qs so or rt t() and b bs se ea ar rc ch h() functions are presented in < c cs st td dl li ib b> and < read more..

  • Page - 558

    Section 18.13 Exercises 547 18.13 Exercises [algo.exercises] The solutions to several exercises for this chapter can be found by looking at the source text of an implementation of the standard library. Do yourself a favor: try to find your own solutions before looking to see how your library implementer approached the problems. 1. ( ∗2) Learn O O() notation. Give a realistic read more..

  • Page - 559

    548 Algorithms and Function Objects Chapter 18 19. ( ∗2) There is no s so or rt t() for bidirectional iterators. The conjecture is that copying to a vector and then sorting is faster than sorting a sequence using bidirectional iterators. Implement a gen- eral sort for bidirectional iterators and test the conjecture. 20. ( ∗2.5) Imagine that you keep records for a group read more..

  • Page - 560

    _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 19 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Iterators and Allocators The reason that data structures and read more..

  • Page - 561

    550 Iterators and Allocators Chapter 19 19.2 Iterators and Sequences [iter.iter] An iterator is a pure abstraction. That is, anything that behaves like an iterator is an iterator (§3.8.2). An iterator is an abstraction of the notion of a pointer to an element of a sequence. Its key concepts are – ‘‘the element currently pointed to’’ (dereferencing, represented by operators * and read more..

  • Page - 562

    Section 19.2.1 Iterator Operations 551 _ _________________________________________________________________________ Iterator Operations and Categories _ _________________________________________________________________________ _ _________________________________________________________________________ Category: output input forward bidirectional random-access Abbreviation: O Ou ut t I In n F Fo or r B Bi i R Ra an n _ read more..

  • Page - 563

    552 Iterators and Allocators Chapter 19 19.2.2 Iterator Traits [iter.traits] We use iterators to gain information about the objects they point to and the sequences they point into. For example, we can dereference an iterator and manipulate the resulting object and we can find the number of elements in a sequence, given the iterators that describe it. To express such operations, read more..

  • Page - 564

    Section 19.2.2 Iterator Traits 553 However, this would have solved the problem for c co ou un nt t() only. Had we used this technique for a dozen algorithms, the information about distance types would have been replicated a dozen times. In general, it is better to represent a design decision in one place (§23.4.2). In that way, the deci- sion can – if necessary – read more..

  • Page - 565

    554 Iterators and Allocators Chapter 19 s st tr ru uc ct t i in np pu ut t _ _i it te er ra at to or r _ _t ta ag g {}; s st tr ru uc ct t o ou ut tp pu ut t _ _i it te er ra at to or r _ _t ta ag g {}; s st tr ru uc ct t f fo or rw wa ar rd d _ _i it te er ra at to or r _ _t ta ag g : p pu ub bl li ic c read more..

  • Page - 566

    Section 19.2.3 Iterator Categories 555 For a d di is st t _ _h he el lp pe er r() to be called, the i it te er ra at to or r _ _t tr ra ai it ts s<I In n>: : i it te er ra at to or r _ _c ca at te eg go or ry y used must be a i in np pu ut t _ _i it te er ra at to or r _ _t ta ag g or a r ra an nd do om m _ read more..

  • Page - 567

    556 Iterators and Allocators Chapter 19 When written to, an inserter inserts a new element into a sequence using p pu us sh h _ _b ba ac ck k(), p pu us sh h _ _f fr ro on nt t(), or i in ns se er rt t() (§16.3.6) rather than overwriting an existing element. For example: v vo oi id d g g(v ve ec ct to or r<i in nt t>& v vi i) { f fi il ll read more..

  • Page - 568

    Section 19.2.5 Reverse Iterators 557 19.2.5 Reverse Iterators [iter.reverse] The standard containers provide r rb be eg gi in n() and r re en nd d() for iterating through elements in reverse order (§16.3.2). These member functions return r re ev ve er rs se e _ _i it te er ra at to or rs: t te em mp pl la at te e < c cl la as ss s I It te er read more..

  • Page - 569

    558 Iterators and Allocators Chapter 19 19.2.6 Stream Iterators [iter.stream] Ordinarily, I/O is done using the streams library (Chapter 21), a graphical user-interface system (not covered by the C++ standard), or the C I/O functions (§21.8). These I/O interfaces are primar- ily aimed at reading and writing individual values of a variety of types. The standard library pro- vides read more..

  • Page - 570

    Section 19.2.6 Stream Iterators 559 An input iterator for i is st tr re ea am ms is defined analogously: t te em mp pl la at te e < c cl la as ss s T T, c cl la as ss s C Ch h = c ch ha ar r, c cl la as ss s T Tr r = c ch ha ar r _ _t tr ra ai it ts s<C Ch h>, c cl la as ss s D Di is st t = p pt tr rd di read more..

  • Page - 571

    560 Iterators and Allocators Chapter 19 t te em mp pl la at te e<c cl la as ss s C Ch h, c cl la as ss s T Tr r = c ch ha ar r _ _t tr ra ai it ts s<C Ch h> > c cl la as ss s i is st tr re ea am mb bu uf f _ _i it te er ra at to or r : p pu ub bl li ic c i it te er ra at to or r<i in np pu ut t read more..

  • Page - 572

    Section 19.2.6.1 Stream Buffers 561 t ty yp pe ed de ef f b ba as si ic c _ _s st tr re ea am mb bu uf f<C Ch h,T Tr r> s st tr re ea am mb bu uf f _ _t ty yp pe e; t ty yp pe ed de ef f b ba as si ic c _ _o os st tr re ea am m<C Ch h,T Tr r> o os st tr re ea am m _ _t ty yp pe e; o os st tr re ea read more..

  • Page - 573

    562 Iterators and Allocators Chapter 19 v vo oi id d f f(v ve ec ct to or r<i in nt t>& v v, c co on ns st t v ve ec ct to or r<i in nt t>& v vc c) { t ty yp pe ed de ef f C Ch he ec ck ke ed d _ _i it te er r<v ve ec ct to or r<i in nt t>,v ve ec ct to or r<i in nt t>: : i it te er ra at read more..

  • Page - 574

    Section 19.3 Checked Iterators 563 The C Ch he ec ck ke ed d _ _i it te er r operations are all fairly trivial: t te em mp pl la at te e<c cl la as ss s C Co on nt t, c cl la as ss s I It te er r = t ty yp pe en na am me e C Co on nt t: : i it te er ra at to or r> c cl la as ss s C Ch he ec ck ke ed d _ _i read more..

  • Page - 575

    564 Iterators and Allocators Chapter 19 C Ch he ec ck ke ed d _ _i it te er r o op pe er ra at to or r++(i in nt t) / / postfix ++ { C Ch he ec ck ke ed d _ _i it te er r t tm mp p = * t th hi is s; ++* t th hi is s; / / checked by prefix ++ r re et tu ur rn n t tm mp p; } C Ch he ec ck ke ed d _ _i it te er read more..

  • Page - 576

    Section 19.3 Checked Iterators 565 protect against all such cases, a different and more expensive iterator design would be needed (see §19.6[7]). Note that postincrement (postfix ++ ) involves a temporary and preincrement does not. For this reason, it is best to prefer ++ p p over p p++ for iterators. Because a C Ch he ec ck ke ed d _ _i it te er r keeps a pointer read more..

  • Page - 577

    566 Iterators and Allocators Chapter 19 v vo oi id d g g() { C Ch he ec ck ke ed d _ _i it te er r<i in nt t> p p(v vi i) ; / / .. i in nt t i i = p p.i in nd de ex x() ; / / get current position v vi i.r re es si iz ze e(1 10 00 0) ; / / p becomes invalid p p = C Ch he ec ck ke ed d _ _i it te er r<i in nt read more..

  • Page - 578

    Section 19.4 Allocators 567 19.4 Allocators [iter.alloc] An a al ll lo oc ca at to or r is used to insulate implementers of algorithms and containers that must allocate mem- ory from the details of physical memory. An allocator provides standard ways of allocating and deallocating memory and standard names of types used as pointers and references. Like an iterator, an allocator read more..

  • Page - 579

    568 Iterators and Allocators Chapter 19 An a al ll lo oc ca at te e(n n) operation allocates space for n n objects that can be deallocated by a corresponding call of d de ea al ll lo oc ca at te e(p p,n n). Note that d de ea al ll lo oc ca at te e() also takes a number-of-elements argument n n. This allows for close-to-optimal allocators that maintain read more..

  • Page - 580

    Section 19.4.1 The Standard Allocator 569 p pu ub bl li ic c: e ex xp pl li ic ci it t v ve ec ct to or r(s si iz ze e _ _t ty yp pe e n n, c co on ns st t T T& v va al l = T T() , c co on ns st t A A& a a = A A()) : a al ll lo oc c(a a) { v v = a al ll lo oc c.a al ll lo oc ca at te e(n n) ; f fo or read more..

  • Page - 581

    570 Iterators and Allocators Chapter 19 The indirection frees us from having to mention a al ll lo oc ca at to or r directly. It expresses the L Li in nk k _ _a al ll lo oc c type in terms of a template parameter A A. For example: t te em mp pl la at te e < c cl la as ss s T T, c cl la as ss s A A = a al ll lo oc ca at to or read more..

  • Page - 582

    Section 19.4.2 A User-Defined Allocator 571 P Po oo ol l(P Po oo ol l&) ; / / copy protection v vo oi id d o op pe er ra at to or r=(P Po oo ol l&) ; / / copy protection v vo oi id d g gr ro ow w() ; / / make pool larger p pu ub bl li ic c: P Po oo ol l(u un ns si ig gn ne ed d i in nt t n n) ; / / n is the size of read more..

  • Page - 583

    572 Iterators and Allocators Chapter 19 f fo or r ( c ch ha ar r* p p = s st ta ar rt t; p p<l la as st t; p p+=e es si iz ze e) / / assume sizeof(Link) <=esize r re ei in nt te er rp pr re et t _ _c ca as st t<L Li in nk k*>(p p)->n ne ex xt t = r re ei in nt te er rp pr re et t _ _c ca as st t<L Li in nk read more..

  • Page - 584

    Section 19.4.2 A User-Defined Allocator 573 performance advantages. For example, because of this restriction, memory need not be set aside for allocators in L Li in nk k objects (which are typically parameterized by the allocator of the container for which they are L Li in nk ks; §19.4.1), and operations that may access elements of two sequences (such as s sw wa ap p()) need not check read more..

  • Page - 585

    574 Iterators and Allocators Chapter 19 Consider how the allocator technique could be used when the efficiency constraints of the stan- dard library don’t apply. This would be the case for a nonstandard library that wasn’t meant to deliver high performance for essentially every data structure and every type in a program and for some special-purpose implementations of the read more..

  • Page - 586

    Section 19.4.4 Uninitialized Memory 575 (§19.6[10]). It would clearly be most unfortunate if an uninitialized object escaped from the inter- nals of a container into the hands of general users. Algorithms often require temporary space to perform acceptably. Often, such temporary space is best allocated in one operation but not initialized until a particular location is actually read more..

  • Page - 587

    576 Iterators and Allocators Chapter 19 t te em mp pl la at te e<c cl la as ss s T T, c cl la as ss s A A> T T* t te em mp po or ra ar ry y _ _d du up p(v ve ec ct to or r<T T,A A>& v v) { T T* p p = g ge et t _ _t te em mp po or ra ar ry y _ _b bu uf ff fe er r<T T>(v v.s si iz ze e()).f fi ir read more..

  • Page - 588

    Section 19.4.5 Dynamic Memory 577 i if f ( i in nt t* q q = n ne ew w(n no ot th hr ro ow w) i in nt t[1 10 00 00 00 00 0]) { / / will not throw exception / / allocation succeeded } e el ls se e { / / allocation failed } } This allows us to use pre-exception error-handling strategies for allocation. 19.4.6 C-Style Allocation [iter.c] From C, C++ inherited read more..

  • Page - 589

    578 Iterators and Allocators Chapter 19 [2] Use overloading to provide more-efficient implementations of an algorithm when given as arguments iterators that offer more than minimal support for the algorithm; §19.2.3. [3] Use i it te er ra at to or r _ _t tr ra ai it ts s to express suitable algorithms for different iterator categories; §19.2.2. [4] Remember to use ++ read more..

  • Page - 590

    _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 20 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Strings Prefer the standard to the offbeat. – Strunk read more..

  • Page - 591

    580 Strings Chapter 20 20.2 Characters [string.char] ‘‘Character’’ is itself an interesting concept. Consider the character C C. The C C that you see as a curved line on the page (or screen), I typed into my computer many months ago. There, it lives as the numeric value 6 67 7 in an 8-bit byte. It is the third letter in the Latin alphabet, the usual abbrevia- tion read more..

  • Page - 592

    Section 20.2.1 Character Traits 581 s st ta at ti ic c v vo oi id d a as ss si ig gn n(c ch ha ar r _ _t ty yp pe e&, c co on ns st t c ch ha ar r _ _t ty yp pe e&) ; / / = for char _type / / integer representation of characters: t ty yp pe ed de ef f i in nt t i in nt t _ _t ty yp pe e; / / type of integer value of read more..

  • Page - 593

    582 Strings Chapter 20 t te em mp pl la at te e<> s st tr ru uc ct t c ch ha ar r _ _t tr ra ai it ts s<w wc ch ha ar r _ _t t> { t ty yp pe ed de ef f w wc ch ha ar r _ _t t c ch ha ar r _ _t ty yp pe e; t ty yp pe ed de ef f w wi in nt t _ _t t i in nt t _ _t ty yp pe e; t ty yp pe ed de ef read more..

  • Page - 594

    Section 20.3.1 Types 583 t ty yp pe ed de ef f T Tr r t tr ra ai it ts s _ _t ty yp pe e; / / specific to basic _string t ty yp pe ed de ef f t ty yp pe en na am me e T Tr r: : c ch ha ar r _ _t ty yp pe e v va al lu ue e _ _t ty yp pe e; t ty yp pe ed de ef f A A a al ll lo oc ca at to or r _ _t ty yp read more..

  • Page - 595

    584 Strings Chapter 20 20.3.2 Iterators [string.begin] Like other containers, a s st tr ri in ng g provides iterators for ordinary and reverse iteration: t te em mp pl la at te e<c cl la as ss s C Ch h, c cl la as ss s T Tr r = c ch ha ar r _ _t tr ra ai it ts s<C Ch h>, c cl la as ss s A A = a al ll lo oc ca at to or r<C read more..

  • Page - 596

    Section 20.3.3 Element Access 585 c co on ns st t _ _r re ef fe er re en nc ce e o op pe er ra at to or r[](s si iz ze e _ _t ty yp pe e n n) c co on ns st t; / / unchecked access r re ef fe er re en nc ce e o op pe er ra at to or r[](s si iz ze e _ _t ty yp pe e n n) ; c co on ns st t _ _r re ef fe er re en read more..

  • Page - 597

    586 Strings Chapter 20 s st tr ri in ng g s s4 4(7 7,´a a´) ; / / 7 copies of ’a’; that is "aaaaaaa" s st tr ri in ng g s s5 5 = " F Fr ro od do o"; / / copy of "Frodo" s st tr ri in ng g s s6 6 = s s5 5; / / copy of s5 s st tr ri in ng g s s7 7(s s5 5,3 3,2 2) ; / / s5[3] and s5[4]; that is read more..

  • Page - 598

    Section 20.3.5 Errors 587 v vo oi id d f f() { s st tr ri in ng g s s = " S Sn no ob bo ol l4 4"; s st tr ri in ng g s s2 2(s s,1 10 00 0,2 2) ; / / character position beyond end of string: throw out _of_range() s st tr ri in ng g s s3 3(s s,2 2,1 10 00 0) ; / / character count too large: equivalent to s3(s,2,s.size()– 2) s read more..

  • Page - 599

    588 Strings Chapter 20 b ba as si ic c _ _s st tr ri in ng g& o op pe er ra at to or r=(c co on ns st t b ba as si ic c _ _s st tr ri in ng g& s s) ; b ba as si ic c _ _s st tr ri in ng g& o op pe er ra at to or r=(c co on ns st t C Ch h* p p) ; b ba as si ic c _ _s st tr ri in ng g& o op pe read more..

  • Page - 600

    Section 20.3.7 Conversion to C-Style Strings 589 20.3.7 Conversion to C-Style Strings [string.conv] As shown in §20.3.4, a s st tr ri in ng g can be initialized by a C-style string and C-style strings can be assigned to s st tr ri in ng gs. Conversely, it is possible to place a copy of the characters of a s st tr ri in ng g into an array: t te em mp pl la read more..

  • Page - 601

    590 Strings Chapter 20 c ch ha ar r* c c _ _s st tr ri in ng g(c co on ns st t s st tr ri in ng g& s s) { c ch ha ar r* p p = n ne ew w c ch ha ar r[s s.l le en ng gt th h()+1 1] ; / / note: +1 s s.c co op py y(p p,s st tr ri in ng g: : n np po os s) ; p p[s s.l le en ng gt th h()] = 0 0; / / note: add read more..

  • Page - 602

    Section 20.3.8 Comparisons 591 When an argument n n is supplied, only the n n first characters will be compared. The comparison cri- terion used is c ch ha ar r _ _t tr ra ai it ts s<C Ch h>’s c co om mp pa ar re e() (§20.2.1). Thus, s s.c co om mp pa ar re e(s s2 2) returns 0 0 if the strings have the same value, a negative number if s s read more..

  • Page - 603

    592 Strings Chapter 20 v vo oi id d f f(c co on ns st t s st tr ri in ng g& n na am me e) { i if f ( n na am me e ==" O Ob be el li ix x" || " A As st te er ri ix x"==n na am me e) { / / use optimized == / / ... } } 20.3.9 Insert [string.insert] Once created, a string can be manipulated in many ways. Of the read more..

  • Page - 604

    Section 20.3.9 Insert 593 s st tr ri in ng g c co om mp pl le et te e _ _n na am me e(c co on ns st t s st tr ri in ng g& f fi ir rs st t _ _n na am me e, c co on ns st t s st tr ri in ng g& f fa am mi il ly y _ _n na am me e) { s st tr ri in ng g s s = f fi ir rs st t _ _n na am me e; s s += ´ read more..

  • Page - 605

    594 Strings Chapter 20 This notational convenience may be bought at the cost of some run-time overhead compared to c co om mp pl le et te e _ _n na am me e(). One extra temporary (§11.3.2) is needed in c co om mp pl le et te e _ _n na am me e3 3(). In my expe- rience, this is rarely important, but it is worth remembering when writing an inner loop of a read more..

  • Page - 606

    Section 20.3.11 Find 595 s si iz ze e _ _t ty yp pe e f fi in nd d _ _l la as st t _ _n no ot t _ _o of f(c co on ns st t b ba as si ic c _ _s st tr ri in ng g& s s, s si iz ze e _ _t ty yp pe e i i = n np po os s) c co on ns st t; s si iz ze e _ _t ty yp pe e f fi in nd d _ _l la as st t _ _n no read more..

  • Page - 607

    596 Strings Chapter 20 / / remove characters from string (‘‘replace with nothing’’): b ba as si ic c _ _s st tr ri in ng g& e er ra as se e(s si iz ze e _ _t ty yp pe e i i = 0 0, s si iz ze e _ _t ty yp pe e n n = n np po os s) ; i it te er ra at to or r e er ra as se e(i it te er ra at to or r i i) ; i it read more..

  • Page - 608

    Section 20.3.13 Substrings 597 B Ba as si ic c _ _s su ub bs st tr ri in ng g& o op pe er ra at to or r=(c co on ns st t b ba as si ic c _ _s st tr ri in ng g<C Ch h>&) ; / / write through to *ps B Ba as si ic c _ _s su ub bs st tr ri in ng g& o op pe er ra at to or r=(c co on ns st t B Ba as si ic read more..

  • Page - 609

    598 Strings Chapter 20 20.3.14 Size and Capacity [string.capacity] Memory-related issues are handled much as they are for v ve ec ct to or r (§16.3.8): t te em mp pl la at te e<c cl la as ss s C Ch h, c cl la as ss s T Tr r = c ch ha ar r _ _t tr ra ai it ts s<C Ch h>, c cl la as ss s A A = a al ll lo oc ca at to or read more..

  • Page - 610

    Section 20.3.16 Swap 599 20.3.16 Swap [string.swap] As for v ve ec ct to or rs (§16.3.9), a s sw wa ap p() function for strings can be much more efficient than the general algorithm, so a specific version is provided: t te em mp pl la at te e<c cl la as ss s C Ch h, c cl la as ss s T Tr r, c cl la as ss s A A> v vo oi id d s sw wa read more..

  • Page - 611

    600 Strings Chapter 20 return 0 0 if the strings are equal, a negative number if the first argument is lexicographically before the second, and a positive number otherwise. Naturally, C doesn’t provide the pairs of overloaded functions. However, they are needed in C++ for c co on ns st t safety. For example: v vo oi id d f f(c co on ns st t c ch ha ar r* p read more..

  • Page - 612

    Section 20.4.1 C-Style Strings 601 example, the value of a at to oi i("s se ev ve en n") is 0 0. If the string represents a number that cannot be repre- sented in the intended result type, e er rr rn no o (§16.1.2, §22.3) is set to E ER RA AN NG GE E and an appropriately huge or tiny value is returned. 20.4.2 Character Classification [string.isalpha] In read more..

  • Page - 613

    602 Strings Chapter 20 [7] Use the f fi in nd d() operations to localize values in a s st tr ri in ng g (rather than writing an explicit loop); §20.3.11. [8] Append to a s st tr ri in ng g when you need to add characters efficiently; §20.3.9. [9] Use s st tr ri in ng gs as targets of non-time-critical character input; §20.3.15. [10] Use s st tr ri in read more..

  • Page - 614

    Section 20.6 Exercises 603 §20.6[7]? Specify and add them. Compare the expressiveness of your regular expression matcher to that of a widely distributed one. Compare the performance of your regular expres- sion matcher to that of a widely distributed one. 9. ( ∗2.5) Use a regular expression library to implement pattern-matching operations on a S St tr ri in ng g class that read more..

  • Page - 615

    604 Strings Chapter 20 The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved. read more..

  • Page - 616

    _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 21 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Streams What you see is all you get. – Brian Kernighan read more..

  • Page - 617

    606 Streams Chapter 21 §21.3 Input: The facilities for requesting input of characters, strings, and values of other built- in and user-defined types are presented. §21.4 Formatting: There are often specific requirements for the layout of the output. For example, i in nt ts may have to be printed in decimal and pointers in hexadecimal or floating-point numbers must appear with read more..

  • Page - 618

    Section 21.1 Introduction 607 The dotted arrow from b ba as si ic c _ _i io os st tr re ea am m<> indicates that b ba as si ic c _ _i io os s<> is a virtual base class; the solid arrows represent pointers. The classes marked with <> are templates parameterized by a character type and containing a l lo oc ca al le e. The streams concept and read more..

  • Page - 619

    608 Streams Chapter 21 used for I/O, I refer to << as put to and to >> as get from. People who prefer more technical- sounding names call them inserters and extractors, respectively. The precedence of << is low enough to allow arithmetic expressions as operands without using parentheses. For example: c co ou ut t << " a a*b b+c c=" << a a*b read more..

  • Page - 620

    Section 21.2.1 Output Streams 609 t te em mp pl la at te e < c cl la as ss s C Ch h, c cl la as ss s T Tr r = c ch ha ar r _ _t tr ra ai it ts s<C Ch h> > c cl la as ss s s st td d: : b ba as si ic c _ _i io os s : p pu ub bl li ic c i io os s _ _b ba as se e { p pu ub bl li ic c: t ty yp pe read more..

  • Page - 621

    610 Streams Chapter 21 b ba as si ic c _ _o os st tr re ea am m& o op pe er ra at to or r<<(f fl lo oa at t f f) ; b ba as si ic c _ _o os st tr re ea am m& o op pe er ra at to or r<<(d do ou ub bl le e f f) ; b ba as si ic c _ _o os st tr re ea am m& o op pe er ra at to or r<<(l lo on read more..

  • Page - 622

    Section 21.2.2 Output of Built-In Types 611 1 1 0 0 t tr ru ue e f fa al ls se e More precisely, b bo oo ol la al lp ph ha a ensures that we get a locale-dependent representation of b bo oo ol l values. By setting my locale (§21.7) just right, I can get: 1 1 0 0 s sa an nd dt t f fa al ls sk k Formatting floating-point numbers, the base used for read more..

  • Page - 623

    612 Streams Chapter 21 21.2.3 Output of User-Defined Types [io.out.udt] Consider a user-defined type c co om mp pl le ex x (§11.3): c cl la as ss s c co om mp pl le ex x { p pu ub bl li ic c: d do ou ub bl le e r re ea al l() c co on ns st t { r re et tu ur rn n r re e; } d do ou ub bl le e i im ma ag g() c co on ns st read more..

  • Page - 624

    Section 21.2.3.1 Virtual Output Functions 613 c cl la as ss s M My y _ _b ba as se e { p pu ub bl li ic c: / / ... v vi ir rt tu ua al l o os st tr re ea am m& p pu ut t(o os st tr re ea am m& s s) c co on ns st t = 0 0; / / write *this to s }; o os st tr re ea am m& o op pe er ra at to or r<<(o os read more..

  • Page - 625

    614 Streams Chapter 21 Two standard input streams c ci in n and w wc ci in n are provided in < i io os st tr re ea am m>: t ty yp pe ed de ef f b ba as si ic c _ _i is st tr re ea am m<c ch ha ar r> i is st tr re ea am m; t ty yp pe ed de ef f b ba as si ic c _ _i is st tr re ea am m<w wc ch ha ar r _ read more..

  • Page - 626

    Section 21.3.2 Input of Built-In Types 615 A non-i in nt t on the input will cause the input operation to fail and thus terminate the input loop. For example, the input: 1 1 2 2 3 3 4 4 5 5.6 6 7 7 8 8. will have r re ea ad d _ _i in nt ts s() read in the five integers 1 1 2 2 3 3 4 4 5 5 and leave the dot as the next character to be read more..

  • Page - 627

    616 Streams Chapter 21 t te em mp pl la at te e<c cl la as ss s C Ch h, c cl la as ss s T Tr r> b ba as si ic c _ _i is st tr re ea am m<C Ch h,T Tr r>& o op pe er ra at to or r>>(b ba as si ic c _ _i is st tr re ea am m<C Ch h,T Tr r>&, C Ch h*) ; t te em mp pl la at te e<c cl la as read more..

  • Page - 628

    Section 21.3.3 Stream State 617 operation might succeed; otherwise, it will fail. Applying an input operation to a stream that is not in the g go oo od d() state is a null operation. If we try to read into a variable v v and the operation fails, the value of v v should be unchanged (it is unchanged if v v is a variable of one of the types handled by i is read more..

  • Page - 629

    618 Streams Chapter 21 v vo oi id d f f(i is st tr re ea am m& i i1 1, i is st tr re ea am m& i i2 2, i is st tr re ea am m& i i3 3, i is st tr re ea am m& i i4 4) { i io oc co op py y<c co om mp pl le ex x>(i i1 1,c co ou ut t) ; / / copy complex numbers i io oc co op py y<d do ou ub bl le read more..

  • Page - 630

    Section 21.3.4 Input of Characters 619 must point to an array of at least n n characters. The third argument, t te er rm m, specifies a terminator. A typical use of the three-argument g ge et t() is to read a ‘‘line’’ into a fixed-sized buffer for further analysis. For example: v vo oi id d f f() { c ch ha ar r b bu uf f[1 10 00 0] ; c ci in n >> read more..

  • Page - 631

    620 Streams Chapter 21 For all of these functions, it is not immediately obvious what terminated the read – and it can be hard even to remember which function has what termination criterion. However, we can always inquire whether we reached end-of-file (§21.3.3). Also, g gc co ou un nt t() gives the number of characters read from the stream by the most recent, read more..

  • Page - 632

    Section 21.3.4 Input of Characters 621 i is st tr re ea am m& e ea at tw wh hi it te e(i is st tr re ea am m& i is s) { c ch ha ar r c c; w wh hi il le e ( i is s.g ge et t(c c)) { i if f (! i is ss sp pa ac ce e(c c)) { / / is c a whitespace character? i is s.p pu ut tb ba ac ck k(c c) ; / / put c back into read more..

  • Page - 633

    622 Streams Chapter 21 The operation for setting a stream state is called c cl le ea ar r() because its most common use is to reset the state of a stream to g go oo od d(); i io os s _ _b ba as se e: : g go oo od db bi it t is the default argument value for i io os s _ _b ba as se e: : c cl le ea ar r() (§21.3.3). 21.3.6 Exceptions read more..

  • Page - 634

    Section 21.3.6 Exceptions 623 v vo oi id d r re ea ad di in nt ts s(v ve ec ct to or r<i in nt t>& s s) / / not my favorite style! { i io os s _ _b ba as se e: : i io os st ta at te e o ol ld d _ _s st ta at te e = c ci in n.e ex xc ce ep pt ti io on ns s() ; / / save exception state c ci in n.e ex xc ce ep read more..

  • Page - 635

    624 Streams Chapter 21 When an o os st tr re ea am m is tied to an i is st tr re ea am m, the o os st tr re ea am m is flushed whenever an input operation on the i is st tr re ea am m causes underflow; that is, whenever new characters are needed from the ultimate input source to complete the input operation. Thus, c co ou ut t << " P read more..

  • Page - 636

    Section 21.3.8 Sentries 625 t te em mp pl la at te e < c cl la as ss s C Ch h, c cl la as ss s T Tr r = c ch ha ar r _ _t tr ra ai it ts s<C Ch h> > b ba as si ic c _ _o os st tr re ea am m<C Ch h,T Tr r>& b ba as si ic c _ _o os st tr re ea am m<C Ch h,T Tr r>: : o op pe er ra at to or read more..

  • Page - 637

    626 Streams Chapter 21 b bo oo ol la al lp ph ha a, / / use symbolic representation of true and false d de ec c, / / integer base: base 10 output (decimal) h he ex x, / / base 16 output (hexadecimal) o oc ct t, / / base 8 output (octal) s sc ci ie en nt ti if fi ic c, / / floating-point notation: d.ddddddEdd f fi ix xe ed d, / / dddd.dd s sh ho read more..

  • Page - 638

    Section 21.4.1 Format State 627 Being able to read and set all options allows us to set an individual flag. For example: m my yo os st tr re ea am m.f fl la ag gs s(m my yo os st tr re ea am m.f fl la ag gs s()|i io os s _ _b ba as se e: : s sh ho ow wp po os s) ; This makes m my ys st tr re ea am m display an explicit + in front read more..

  • Page - 639

    628 Streams Chapter 21 c co ou ut t.s se et tf f(i io os s _ _b ba as se e: : o oc ct t,i io os s _ _b ba as se e: : b ba as se ef fi ie el ld d) ; / / octal c co ou ut t << 1 12 23 34 4 << ´ ´ << 1 12 23 34 4 << ´ ´; c co ou ut t.s se et tf f(i io os s _ _b ba as se e: : h he ex x,i io read more..

  • Page - 640

    Section 21.4.3 Floating-Point Output 629 c cl la as ss s i io os s _ _b ba as se e { p pu ub bl li ic c: / / ... s st tr re ea am ms si iz ze e p pr re ec ci is si io on n() c co on ns st t; / / get precision s st tr re ea am ms si iz ze e p pr re ec ci is si io on n(s st tr re ea am ms si iz ze e n n) ; / / read more..

  • Page - 641

    630 Streams Chapter 21 The w wi id dt th h() function specifies the minimum number of characters to be used for the next standard library << output operation of a numeric value, b bo oo ol l, C-style string, character, pointer (§21.2.1), s st tr ri in ng g (§20.3.15), and b bi it tf fi ie el ld d (§17.5.3.3). For example, c co ou ut t.w wi id dt th h(4 read more..

  • Page - 642

    Section 21.4.5 Field Adjustment 631 Adjustment can be specified like this: c co ou ut t.f fi il ll l(´#´) ; c co ou ut t << ´(´; c co ou ut t.w wi id dt th h(4 4) ; c co ou ut t << - 1 12 2 << ") ,("; c co ou ut t.w wi id dt th h(4 4) ; c co ou ut t.s se et tf f(i io os s _ _b ba as se e: : l le ef ft t,i read more..

  • Page - 643

    632 Streams Chapter 21 These declarations ensure that c co ou ut t << f fl lu us sh h; is resolved as c co ou ut t.o op pe er ra at to or r<<(f fl lu us sh h) ; which calls f fl lu us sh h(c co ou ut t) ; which then invokes c co ou ut t.f fl lu us sh h() ; The whole rigmarole is done (at compile time) to allow b ba as si ic c read more..

  • Page - 644

    Section 21.4.6.1 Manipulators Taking Arguments 633 21.4.6.1 Manipulators Taking Arguments [io.manip.arg] Manipulators that take arguments can also be useful. For example, we might want to write c co ou ut t << s se et tp pr re ec ci is si io on n(4 4) << a an ng gl le e; to print the value of the floating-point variable a an ng gl le e with four digits. read more..

  • Page - 645

    634 Streams Chapter 21 i io os s _ _b ba as se e& b bo oo ol la al lp ph ha a(i io os s _ _b ba as se e&) ; / / symbolic representation of true and false (input and output) i io os s _ _b ba as se e& n no ob bo oo ol la al lp ph ha a(i io os s _ _b ba as se e& s s) ; / / s.unsetf(ios _base::boolalpha) i io os s _ _b read more..

  • Page - 646

    Section 21.4.6.2 Standard I/O Manipulators 635 When using manipulators that do not take arguments, do not add parentheses. When using stan- dard manipulators that take arguments, remember to # i in nc cl lu ud de e < i io om ma an ni ip p>. For example: # i in nc cl lu ud de e < i io os st tr re ea am m> i in nt t m ma ai in n() { s st td read more..

  • Page - 647

    636 Streams Chapter 21 p pu ub bl li ic c: e ex xp pl li ic ci it t F Fo or rm m(i in nt t p p = 6 6) : p pr rc c(p p) / / default precision is 6 { f fm mt t = 0 0; / / general format (§21.4.3) w wd dt t = 0 0; / / as wide as necessary } B Bo ou un nd d _ _f fo or rm m o op pe er ra at to or r()(d do ou ub bl le e read more..

  • Page - 648

    Section 21.5 File Streams and String Streams 637 21.5 File Streams and String Streams [io.files] When a C++ program starts, c co ou ut t, c ce er rr r, c cl lo og g, c ci in n, and their wide-character equivalents (§21.2.1) are available for use. These streams are set up by default and their correspondence with I/O devices or files is determined by ‘‘the read more..

  • Page - 649

    638 Streams Chapter 21 v vo oi id d e er rr ro or r(c co on ns st t c ch ha ar r* p p, c co on ns st t c ch ha ar r* p p2 2 = "") { c ce er rr r << p p << ´ ´ << p p2 2 << ´ \ \n n´; s st td d: : e ex xi it t(1 1) ; } i in nt t m ma ai in n(i in nt t a ar rg gc c, c ch ha ar read more..

  • Page - 650

    Section 21.5.1 File Streams 639 File stream constructors take a second argument specifying alternative modes of opening: c cl la as ss s i io os s _ _b ba as se e { p pu ub bl li ic c: / / ... t ty yp pe ed de ef f implementation _defined3 o op pe en nm mo od de e; s st ta at ti ic c o op pe en nm mo od de e a ap pp p, / / append a at read more..

  • Page - 651

    640 Streams Chapter 21 c cl la as ss s i io os s _ _b ba as se e: : I In ni it t { s st ta at ti ic c i in nt t c co ou un nt t; p pu ub bl li ic c: I In ni it t() ; ~ I In ni it t() ; }; n na am me es sp pa ac ce e { / / in <iostream>, one copy in each file #including <iostream> i io os s _ _b ba as se e: : read more..

  • Page - 652

    Section 21.5.3 String Streams 641 b ba as si ic c _ _s st tr ri in ng g<C Ch h> s st tr r() c co on ns st t; / / get copy of string v vo oi id d s st tr r(c co on ns st t b ba as si ic c _ _s st tr ri in ng g<C Ch h>& s s) ; / / set value to copy of s b ba as si ic c _ _s st tr ri in ng gb bu uf f<C read more..

  • Page - 653

    642 Streams Chapter 21 It is possible to define streams that directly read from and write to arrays of characters (§21.10[26]). This is often useful when dealing with older code, especially since the o os st tr rs st tr re ea am m and i is st tr rs st tr re ea am m classes doing that were part of the original streams library. 21.6 Buffering [io.buf] read more..

  • Page - 654

    Section 21.6.1 Output Streams and Buffers 643 b ba as si ic c _ _o os st tr re ea am m& o op pe er ra at to or r<<(b ba as si ic c _ _s st tr re ea am mb bu uf f<C Ch h,T Tr r>* b b) ; / / write from b }; An o os st tr re ea am m is constructed with a s st tr re ea am mb bu uf f argument, which determines how the read more..

  • Page - 655

    644 Streams Chapter 21 p po os s _ _t ty yp pe e t te el ll lg g() ; / / get current position b ba as si ic c _ _i is st tr re ea am m& s se ee ek kg g(p po os s _ _t ty yp pe e) ; / / set current position b ba as si ic c _ _i is st tr re ea am m& s se ee ek kg g(o of ff f _ _t ty yp pe e, i io os s _ _b read more..

  • Page - 656

    Section 21.6.3 Streams and Buffers 645 l lo oc ca al le e i im mb bu ue e(c co on ns st t l lo oc ca al le e& l lo oc c) ; / / set locale (and get old locale) c ch ha ar r n na ar rr ro ow w(c ch ha ar r _ _t ty yp pe e c c, c ch ha ar r d d) c co on ns st t; / / make char value from char _type c c ch ha ar r _ read more..

  • Page - 657

    646 Streams Chapter 21 C Ch h* p pb ba as se e() c co on ns st t; / / start of put-buffer C Ch h* p pp pt tr r() c co on ns st t; / / next free char (next char written goes here) C Ch h* e ep pp pt tr r() c co on ns st t; / / one-past-end of put-buffer v vo oi id d p pb bu um mp p(i in nt t n n) ; / / add n to pptr() v vo read more..

  • Page - 658

    Section 21.6.4 Stream Buffers 647 / / ... }; The public interface contains functions for inserting characters into the buffer and extracting char- acters from the buffer. These functions are simple and easily inlined. This is crucial for efficiency. Functions that implement parts of a specific buffering strategy invoke corresponding functions in the protected interface. For example, p pu read more..

  • Page - 659

    648 Streams Chapter 21 v vi ir rt tu ua al l i in nt t s sh ho ow wm ma an ny yc c() ; v vi ir rt tu ua al l s st tr re ea am ms si iz ze e x xs sg ge et tn n(C Ch h* p p, s st tr re ea am ms si iz ze e n n) ; / / get n chars v vi ir rt tu ua al l i in nt t _ _t ty yp pe e u un nd de er rf fl lo ow read more..

  • Page - 660

    Section 21.6.4 Stream Buffers 649 v vi ir rt tu ua al l i in nt t _ _t ty yp pe e p pb ba ac ck kf fa ai il l(i in nt t _ _t ty yp pe e c c = T Tr r: : e eo of f()) ; v vi ir rt tu ua al l i in nt t _ _t ty yp pe e o ov ve er rf fl lo ow w(i in nt t _ _t ty yp pe e c c = T Tr r: : e eo of f()) ; v vi read more..

  • Page - 661

    650 Streams Chapter 21 v vo oi id d f f() { s st td d: : l lo oc ca al le e l lo oc c("P PO OS SI IX X") ; / / standard locale for POSIX c ci in n.i im mb bu ue e(l lo oc c) ; / / let cin use loc / / ... c ci in n.i im mb bu ue e(s st td d: : l lo oc ca al le e: : g gl lo ob ba al l()) ; / / reset cin to use read more..

  • Page - 662

    Section 21.7.1 Stream Callbacks 651 / / callbacks: e en nu um m e ev ve en nt t { e er ra as se e _ _e ev ve en nt t, i im mb bu ue e _ _e ev ve en nt t, c co op py yf fm mt t _ _e ev ve en nt t }; / / event type t ty yp pe ed de ef f v vo oi id d (* e ev ve en nt t _ _c ca al ll lb ba ac ck k)(e ev ve en nt read more..

  • Page - 663

    652 Streams Chapter 21 Here % d d specifies that n no o _ _o of f _ _m me em mb be er rs s is to be treated as an i in nt t and printed as the appropriate sequence of decimal digits. With n no o _ _o of f _ _m me em mb be er rs s==1 12 27 7, the output is t th he er re e w we er re e 1 12 27 7 m me em mb be er rs s p pr read more..

  • Page - 664

    Section 21.8 C Input/Output 653 E As e e, but with an uppercase E E used to identify the exponent; g The f fl lo oa at t or d do ou ub bl le e argument is printed in style d, in style f, or in style e, whichever gives the greatest precision in minimum space; G As g g, but with an uppercase E E used to identify the exponent. c The character argument is read more..

  • Page - 665

    654 Streams Chapter 21 For further details of C I/O, see your C reference manual or Kernighan and Ritchie: The C Pro- gramming Language [Kernighan,1988]. 21.9 Advice [io.advice] [1] Define << and >> for user-defined types with values that have meaningful textural representa- tions; §21.2.3, §21.3.5. [2] Use parentheses when printing expressions containing operators of low read more..

  • Page - 666

    Section 21.10 Exercises 655 21.10 Exercises [io.exercises] 1. ( ∗1.5) Read a file of floating-point numbers, make complex numbers out of pairs of numbers read, and write out the complex numbers. 2. ( ∗1.5) Define a type N Na am me e _ _a an nd d _ _a ad dd dr re es ss s. Define << and >> for it. Copy a stream of N Na am me e _ _a an nd d _ read more..

  • Page - 667

    656 Streams Chapter 21 18. ( ∗2) Define an output manipulator b ba as se ed d that takes two arguments – a base and an i in nt t value – and outputs the integer in the representation specified by the base. For example, b ba as se ed d(2 2,9 9) should print 1 10 00 01 1. 19. ( ∗2) Write manipulators that turn character echoing on and off. 20. ( ∗2) read more..

  • Page - 668

    _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 22 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Numerics The purpose of computing is insight, not numbers. read more..

  • Page - 669

    658 Numerics Chapter 22 computations in C++. I make no attempt to teach numeric methods. Numeric computation is a fas- cinating topic in its own right. To understand it, you need a good course in numerical methods or at least a good textbook – not just a language manual and tutorial. 22.2 Numeric Limits [num.limits] To do anything interesting with numbers, we typically need read more..

  • Page - 670

    Section 22.2 Numeric Limits 659 c cl la as ss s n nu um me er ri ic c _ _l li im mi it ts s<c ch ha ar r> { p pu ub bl li ic c: s st ta at ti ic c c co on ns st t b bo oo ol l i is s _ _s sp pe ec ci ia al li iz ze ed d = t tr ru ue e; / / yes, we have information s st ta at ti ic c c co on ns st t i read more..

  • Page - 671

    660 Numerics Chapter 22 s st ta at ti ic c c co on ns st t b bo oo ol l t tr ra ap ps s = t tr ru ue e; s st ta at ti ic c c co on ns st t b bo oo ol l t ti in ny yn ne es ss s _ _b be ef fo or re e = t tr ru ue e; s st ta at ti ic c c co on ns st t f fl lo oa at t _ _r ro ou un nd d _ _s st ty read more..

  • Page - 672

    Section 22.3 Standard Mathematical Functions 661 d do ou ub bl le e c co os s(d do ou ub bl le e) ; / / cosine d do ou ub bl le e s si in n(d do ou ub bl le e) ; / / sine d do ou ub bl le e t ta an n(d do ou ub bl le e) ; / / tangent d do ou ub bl le e a ac co os s(d do ou ub bl le e) ; / / arc cosine d do ou ub bl read more..

  • Page - 673

    662 Numerics Chapter 22 22.4 Vector Arithmetic [num.valarray] Much numeric work relies on relatively simple single-dimensional vectors of floating-point values. In particular, such vectors are well supported by high-performance machine architectures, libraries relying on such vectors are in wide use, and very aggressive optimization of code using such vectors is considered essential in many read more..

  • Page - 674

    Section 22.4.1 Valarray Construction 663 This set of constructors allows us to initialize v va al la ar rr ra ay ys from the auxiliary numeric array types and from single values. For example: v va al la ar rr ra ay y<d do ou ub bl le e> v v0 0; / / placeholder, we can assign to v0 later v va al la ar rr ra ay y<f fl lo oa at t> v v1 1(1 read more..

  • Page - 675

    664 Numerics Chapter 22 v va al la ar rr ra ay y o op pe er ra at to or r[](s sl li ic ce e) c co on ns st t; / / see §22.4.6 s sl li ic ce e _ _a ar rr ra ay y<T T> o op pe er ra at to or r[](s sl li ic ce e) ; v va al la ar rr ra ay y o op pe er ra at to or r[](c co on ns st t g gs sl li ic ce e&) read more..

  • Page - 676

    Section 22.4.3 Member Operations 665 v va al la ar rr ra ay y s sh hi if ft t(i in nt t i i) c co on ns st t; / / logical shift (left for 0 <i, right for i <0) v va al la ar rr ra ay y c cs sh hi if ft t(i in nt t i i) c co on ns st t; / / cyclic shift (left for 0 <i, right for i <0) v va al la ar rr ra ay y a ap pp pl read more..

  • Page - 677

    666 Numerics Chapter 22 operators (§22.4.4). Consequently, <<= and >>= can be used to shift bits within elements of an integral type. For example: v vo oi id d f f(v va al la ar rr ra ay y<i in nt t> v vi i, v va al la ar rr ra ay y<d do ou ub bl le e> v vd d) { v vi i <<= 2 2; / / vi[i] <<=2 for all elements of vi read more..

  • Page - 678

    Section 22.4.3 Member Operations 667 If we want a v va al la ar rr ra ay y holding valuable data to grow dynamically, we must use a temporary: v vo oi id d g gr ro ow w(v va al la ar rr ra ay y<i in nt t>& v v, s si iz ze e _ _t t n n) { i if f ( n n<=v v.s si iz ze e()) r re et tu ur rn n; v va al la ar rr ra ay read more..

  • Page - 679

    668 Numerics Chapter 22 v vo oi id d f f(v va al la ar rr ra ay y<d do ou ub bl le e>& v v, v va al la ar rr ra ay y<d do ou ub bl le e>& v v2 2, d do ou ub bl le e d d) { v va al la ar rr ra ay y<d do ou ub bl le e> v v3 3 = v v*v v2 2; / / v3[i] = v[i]*v2[i] for all i v va al la ar rr ra ay read more..

  • Page - 680

    Section 22.4.5 Slices 669 s si iz ze e _ _t t s sl li ic ce e _ _i in nd de ex x(c co on ns st t s sl li ic ce e& s s, s si iz ze e _ _t t i i) / / map i to its corresponding index { r re et tu ur rn n s s.s st ta ar rt t()+i i*s s.s st tr ri id de e() ; } v vo oi id d p pr ri in nt t _ _s se eq q(c co on read more..

  • Page - 681

    670 Numerics Chapter 22 Row x x can be described by a s sl li ic ce e(x x,3 3,4 4). That is, the first element of row x x is the x xth ele- ment of the vector, the next element of the row is the ( x x+4 4)th, etc., and there are 3 3 elements in each row. In the figures, s sl li ic ce e(0 0,3 3,4 4) describes the row 0 00 0, 0 01 1, and read more..

  • Page - 682

    Section 22.4.5 Slices 671 t te em mp pl la at te e<c cl la as ss s T T> b bo oo ol l o op pe er ra at to or r!=(c co on ns st t S Sl li ic ce e _ _i it te er r<T T>& p p, c co on ns st t S Sl li ic ce e _ _i it te er r<T T>& q q) { r re et tu ur rn n !( p p==q q) ; } t te em mp pl la at read more..

  • Page - 683

    672 Numerics Chapter 22 s sl li ic ce e _ _a ar rr ra ay y<d do ou ub bl le e> r ro ow w(v va al la ar rr ra ay y<d do ou ub bl le e>& d d, i in nt t i i) { s sl li ic ce e _ _a ar rr ra ay y<d do ou ub bl le e> v v = d d[s sl li ic ce e(0 0,2 2,d d.s si iz ze e()/2 2)] ; / / error: attempt to read more..

  • Page - 684

    Section 22.4.6 Slice _array 673 S Sl li ic ce e _ _i it te er r<d do ou ub bl le e> c co ol lu um mn n(s si iz ze e _ _t t i i) ; C Cs sl li ic ce e _ _i it te er r<d do ou ub bl le e> c co ol lu um mn n(s si iz ze e _ _t t i i) c co on ns st t; d do ou ub bl le e& o op pe er ra at to or r()(s si read more..

  • Page - 685

    674 Numerics Chapter 22 M Ma at tr ri ix x: : M Ma at tr ri ix x(s si iz ze e _ _t t x x, s si iz ze e _ _t t y y) { / / check that x and y are sensible d d1 1 = x x; d d2 2 = y y; v v = n ne ew w v va al la ar rr ra ay y<d do ou ub bl le e>(x x*y y) ; } d do ou ub bl le e& M Ma at tr ri ix x: : o op read more..

  • Page - 686

    Section 22.4.6 Slice _array 675 c cl la as ss s M Ma at tr ri ix x { v va al la ar rr ra ay y< v va al la ar rr ra ay y<d do ou ub bl le e> > v v; p pu ub bl li ic c: / / ... }; This would also work (§22.9[10]). However, it is not easy to match the efficiency and compatibil- ity required by high-performance computations without read more..

  • Page - 687

    676 Numerics Chapter 22 This ‘‘multiplication’’ does nothing except store references to its operands; the evaluation of M M*V V is deferred. The object produced by * is closely related to what is called a c cl lo os su ur re e in many techni- cal communities. Similarly, we can deal with what happens if we add a V Ve ec ct to or r: s st tr ru uc ct t M read more..

  • Page - 688

    Section 22.4.7 Temporaries, Copying, and Loops 677 The importance of this technique is that most really time-critical vector and matrix computa- tions are done using a few relatively simple syntactic forms. Typically, there is no real gain in opti- mizing expressions of half-a-dozen operators this way; more conventional techniques (§11.6) suf- fice. This technique is based on the idea read more..

  • Page - 689

    678 Numerics Chapter 22 elements of a row of the 3-by-4 matrix, when Fortran layout is used. Similarly, a length of 3 3 and a stride of 1 1 describes 3 elements of a column. Together, they describe every element of the 2-by-3 submatrix. To list the elements, we can write: s si iz ze e _ _t t g gs sl li ic ce e _ _i in nd de ex x(c co on ns st t g read more..

  • Page - 690

    Section 22.4.9 Masks 679 v vo oi id d f f(v va al la ar rr ra ay y<d do ou ub bl le e>& v v) { b bo oo ol l b b[] = { t tr ru ue e , f fa al ls se e, f fa al ls se e, t tr ru ue e, f fa al ls se e, t tr ru ue e }; v va al la ar rr ra ay y<b bo oo ol l> m ma as sk k(b b,6 6) ; / / elements 0, 3, read more..

  • Page - 691

    680 Numerics Chapter 22 t te em mp pl la at te e<c cl la as ss s T T> c cl la as ss s s st td d: : c co om mp pl le ex x { T T r re e, i im m; p pu ub bl li ic c: t ty yp pe ed de ef f T T v va al lu ue e _ _t ty yp pe e; c co om mp pl le ex x(c co on ns st t T T& r r = T T() , c co on ns st read more..

  • Page - 692

    Section 22.5 Complex Arithmetic 681 t te em mp pl la at te e<c cl la as ss s T T> c co om mp pl le ex x<T T> s si in n(c co on ns st t c co om mp pl le ex x<T T>&) ; / / similarly: sinh, sqrt, tan, tanh, cos, cosh, exp, log, and log10 t te em mp pl la at te e<c cl la as ss s T T> c co om mp pl le ex read more..

  • Page - 693

    682 Numerics Chapter 22 22.6 Generalized Numeric Algorithms [num.general] In < n nu um me er ri ic c>, the standard library provides a few generalized numeric algorithms in the style of the non-numeric algorithms from < a al lg go or ri it th hm m> (Chapter 18) : _ __________________________________________________________________ Generalized Numeric Algorithms <numeric> _ read more..

  • Page - 694

    Section 22.6.1 Accumulate 683 s st tr ru uc ct t R Re ec co or rd d { / / ... i in nt t u un ni it t _ _p pr ri ic ce e; i in nt t n nu um mb be er r _ _o of f _ _u un ni it ts s; }; l lo on ng g p pr ri ic ce e(l lo on ng g v va al l, c co on ns st t R Re ec co or rd d& r r) { r re et tu ur rn n v read more..

  • Page - 695

    684 Numerics Chapter 22 v va al la ar rr ra ay y<d do ou ub bl le e> o op pe er ra at to or r*(c co on ns st t v va al la ar rr ra ay y<d do ou ub bl le e>& v v, c co on ns st t M Ma at tr ri ix x& m m) { v va al la ar rr ra ay y<d do ou ub bl le e> r re es s(m m.d di im m2 2()) ; f fo or read more..

  • Page - 696

    Section 22.6.3 Incremental Change 685 t te em mp pl la at te e < c cl la as ss s I In n, c cl la as ss s O Ou ut t> O Ou ut t p pa ar rt ti ia al l _ _s su um m(I In n f fi ir rs st t, I In n l la as st t, O Ou ut t r re es s) { r re et tu ur rn n p pa ar rt ti ia al l _ _s su um m(f fi ir rs st read more..

  • Page - 697

    686 Numerics Chapter 22 c cl la as ss s R Ra an nd di in nt t { / / uniform distribution in the interval [0,max] u un ns si ig gn ne ed d l lo on ng g r ra an nd dx x; p pu ub bl li ic c: R Ra an nd di in nt t(l lo on ng g s s = 0 0) { r ra an nd dx x=s s; } v vo oi id d s se ee ed d(l lo on ng g s s) { r ra read more..

  • Page - 698

    Section 22.8 Advice 687 [4] Use v va al la ar rr ra ay y for numeric computation when run-time efficiency is more important than flexi- bility with respect to operations and element types; §22.4. [5] Express operations on part of an array in terms of slices rather than loops; §22.4.6. [6] Use compositors to gain efficiency through elimination of temporaries and better read more..

  • Page - 699

    688 Numerics Chapter 22 The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved. read more..

  • Page - 700

    Part IV Design Using C+ + This part presents C++ and the techniques it supports in the larger picture of software development. The focus is on design and the effective realization of design in terms of language constructs. Chapters 23 Development and Design 24 Design and Programming 25 Roles of Classes The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 read more..

  • Page - 701

    690 Design Using C++ Part IV ‘‘... I am just now beginning to discover the difficulty of expressing one’s ideas on paper. As long as it consists solely of description it is pretty easy; but where reasoning comes into play, to make a proper connection, a clearness & a moderate fluency, is to me, as I have said, a difficulty of which I had no idea ...’’ – read more..

  • Page - 702

    _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 23 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Development and Design There is no silver bullet. – F. read more..

  • Page - 703

    692 Development and Design Chapter 23 23.2 Introduction [design.intro] Constructing any nontrivial piece of software is a complex and often daunting task. Even for an individual programmer, the actual writing of program statements is only one part of the process. Typically, issues of problem analysis, overall program design, documentation, testing, and mainte- nance, as well as the read more..

  • Page - 704

    Section 23.2 Introduction 693 – There are no ‘‘cookbook’’ methods that can replace intelligence, experience, and good taste in design and programming. – Experimentation is essential for all nontrivial software development. – Design and programming are iterative activities. – The different phases of a software project, such as design, programming, and testing, cannot be strictly read more..

  • Page - 705

    694 Development and Design Chapter 23 In both cases, the selection of the parts and the specification of the interfaces between the parts is where the most experience and taste is required. Such selection is not a simple mechanical pro- cess but typically requires insights that can be achieved only through a thorough understanding of a system at suitable levels of abstraction read more..

  • Page - 706

    Section 23.3 Aims and Means 695 then the users will want to know more ‘‘details’’ to be able to better use the libraries and also to better benefit from them as sources of ideas. A balance has to be struck between the lack of an overall design for a piece of software and overemphasis on structure. The former leads to endless cutting of corners (‘‘we’ll just ship read more..

  • Page - 707

    696 Development and Design Chapter 23 The purpose of ‘‘design’’ is to create a clean and relatively simple internal structure, sometimes also called an architecture, for a program. In other words, we want to create a framework into which the individual pieces of code can fit and thereby guide the writing of those individual pieces of code. A design is the end product of read more..

  • Page - 708

    Section 23.4 The Development Process 697 experience. Furthermore, the design is constrained by schedules, the skills of the people involved, compatibility issues, etc. A major challenge to a designer/manager/programmer is to create order in this process without stifling innovation and destroying the feedback loops that are necessary for successful development. The development process has three read more..

  • Page - 709

    698 Development and Design Chapter 23 relating to the flawed decision that the effort involved in modifying the documentation dwarfs the effort needed to fix the code. In this way, paperwork can become the major problem of software development. Naturally, such problems can – and do – occur however one organizes the develop- ment of large systems. After all, some paperwork is read more..

  • Page - 710

    Section 23.4.1 The Development Cycle 699 components) from scratch. A software designer or programmer in a similar circumstance might unwisely try exactly that. The first stage is to consider which components are available from the factory’s own inventory and from reliable suppliers. The components thus found need not be exactly right for the new car. There will be ways of read more..

  • Page - 711

    700 Development and Design Chapter 23 organization with a life that spans several projects and of a size that makes worthwhile the neces- sary extra investment in tools (for design, programming, and project management) and education (of designers, programmers, and managers). It is a sketch of a kind of software factory. Curiously enough, it differs only in scale from the practices read more..

  • Page - 712

    Section 23.4.2 Design Aims 701 cloud: for example, as a detailed picture, as a rough outline, or as an icon on a map. In other words, what a cloud looks like depends on both the cloud and its environment. A second solution to the problem is to make the cloud aware of its environment and then let the cloud display itself. This solution is acceptable in even more read more..

  • Page - 713

    702 Development and Design Chapter 23 The set of classes in a component is united by some logical criteria, often by a common style and often by a reliance on common services. A component is thus the unit of design, documenta- tion, ownership, and often reuse. This does not mean that if you use one class from a component, you must understand and use all the classes read more..

  • Page - 714

    Section 23.4.3.1 Step 1: Find Classes 703 operations on objects, traditional (global) functions that produce new values based on the value of their arguments, or even classes. As examples of the latter, note the function objects (§18.4) and manipulators (§21.4.6). Verbs such as ‘‘iterate’’ or ‘‘commit’’ can be represented by an iterator object and an object representing a database read more..

  • Page - 715

    704 Development and Design Chapter 23 A use case is a description of a particular use of a system. Here is a simple example of a use case for a telephony system: take the phone off hook, dial a number, the phone at the other end rings, the phone at the other end is taken off hook. Developing a set of such use cases can be of immense value at all stages of read more..

  • Page - 716

    Section 23.4.3.1 Step 1: Find Classes 705 is an invaluable design tool. Preparing a presentation with the aim of conveying real understanding to people with the interest and ability to produce constructive criticism is an exercise in conceptual- ization and clean expression of ideas. However, a formal presentation of a design is also a very dangerous activity because there is a read more..

  • Page - 717

    706 Development and Design Chapter 23 This is clearly a statement of minimalism. It is far easier to add every function that could conceiv- ably be useful and to make all operations virtual. However, the more functions, the more likely they are to remain unused and the more likely they are to constrain the implementation and the fur- ther evolution of the system. In read more..

  • Page - 718

    Section 23.4.3.3 Step 3: Specify Dependencies 707 inefficient and incomprehensible designs by proliferating classes and objects to the point where no work is done except by a cascade of forwarded requests for service. What can be done here and now, should be. The need to consider inheritance and use relationships at the design stage (and not just during implementation) follows read more..

  • Page - 719

    708 Development and Design Chapter 23 Unfortunately, there are no simple, general answers to such questions. This is not really sur- prising because what we are talking about are not minor implementation details, but changes to the basic concepts of a system. The fundamental – and nontrivial – operation is to look for common- ality between classes and factor out the common read more..

  • Page - 720

    Section 23.4.3.6 Use of Models 709 only where the logic of the information I’m trying to convey requires it. For example, this book is written that way based on its first and second editions. An extreme form of this writing technique is the form letter. In that case, I simply fill in a name and maybe add a few lines to ‘‘personalize’’ the letter. In essence, read more..

  • Page - 721

    710 Development and Design Chapter 23 scratch exactly right according to the latest principles. The larger and the more ambitious a system we aim for, the more important it is to have a model from which to work. For a large system, the only really acceptable model is a somewhat smaller, related working system. 23.4.4 Experimentation and Analysis [design.experiment] At the start read more..

  • Page - 722

    Section 23.4.4 Experimentation and Analysis 711 Prototyping is a way of experimenting. The desired results from building a prototype are the insights that building it brings, not the prototype itself. Maybe the most important criterion for a prototype is that it has to be so incomplete that it is obviously an experimental vehicle and cannot be turned into a product without a read more..

  • Page - 723

    712 Development and Design Chapter 23 23.4.5 Testing [design.test] A program that has not been tested does not work. The ideal of designing and/or verifying a pro- gram so that it works the first time is unattainable for all but the most trivial programs. We should strive toward that ideal, but we should not be fooled into thinking that testing is easy. ‘‘How to test?’’ read more..

  • Page - 724

    Section 23.4.6 Software Maintenance 713 involved in a project. It is not easy to successfully transfer maintenance to a new (and typically less-experienced) group of people with no links to the original designers and implementers. When a major change of people is necessary, there must be an emphasis on transferring an understanding of the system’s structure and of the system’s read more..

  • Page - 725

    714 Development and Design Chapter 23 supported by global changes required to ensure its success. A fairly typical example is a change to a language that supports object-oriented programming, such as C++, without a matching change in the design strategies to take advantage of its facilities (see also §24.2). Another is a change to ‘‘object-oriented design’’ without the read more..

  • Page - 726

    Section 23.5.1 Reuse 715 Whenever possible, the members of this group should work in close cooperation with applica- tions builders. Only then can they be sufficiently aware of the needs of users and alert to the oppor- tunities for sharing components among different applications. This argues for there to be a consul- tancy role for such an organization and for the use of read more..

  • Page - 727

    716 Development and Design Chapter 23 Fortunately, most systems do not fall into this category. However, once the idea is accepted that such a design method or adherence to such a set of coding and documentation standards is ‘‘the right way,’’ pressure builds to apply it universally and in every detail. This can lead to ludicrous constraints and overheads on small projects. In read more..

  • Page - 728

    Section 23.5.3 Individuals 717 of number of lines of code produced, a successful application of reuse will appear to cause negative performance of programmers. A successful application of the best principles in the redesign of a major piece of software typically has the same effect. Quality of work produced is far harder to measure than quantity of output, yet individuals and read more..

  • Page - 729

    718 Development and Design Chapter 23 should remember that the most successful ‘‘old timers’’ are often the ‘‘young turks’’ of yesteryear. Given a chance to learn without humiliation, more experienced programmers and designers can become the most successful and insightful proponents of change. Their healthy skepticism, knowl- edge of users, and acquaintance with the organizational read more..

  • Page - 730

    Section 23.5.4 Hybrid Design 719 C++’s notions of data abstraction and object-oriented programming (§24.2.1). Many interfaces can simply be left procedural because there will be no immediate benefits in doing anything more com- plicated. For many key libraries, this will already have been done by the library provider so that the C++ programmer can stay ignorant of the actual read more..

  • Page - 731

    720 Development and Design Chapter 23 [Coplien,1995] James O. Coplien and Douglas C. Schmidt (editors): Pattern Languages of Program Design. Addison-Wesley. 1995. ISBN 1-201-60734-4. [Gamma,1994] Eric Gamma, et. al.: Design Patterns. Addison-Wesley. 1994. ISBN 0- 201-63361-2. A practical catalog of techniques for creating flexible and reusable software, with a nontrivial, well-explained example. read more..

  • Page - 732

    Section 23.6 Annotated Bibliography 721 first good description of the interaction between encapsulation and inheri- tance. Also provides a nice discussion of some notions of multiple inheri- tance. [Wirfs-Brock,1990] Rebecca Wirfs-Brock, Brian Wilkerson, and Lauren Wiener: Designing Object-Oriented Software. Prentice Hall. 1990. Describes an anthropo- morphic design method based on role playing read more..

  • Page - 733

    722 Development and Design Chapter 23 [28] Always consider alternative representations for a class. If no alternative representation is plau- sible, the class is probably not representing a clean concept; §23.4.3.4. [29] Repeatedly review and refine both the design and the implementation; §23.4, §23.4.3. [30] Use the best tools available for testing and for analyzing the problem, the read more..

  • Page - 734

    _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 24 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Design and Programming Keep it simple: as simple as read more..

  • Page - 735

    724 Design and Programming Chapter 24 24.2 Design and Programming Language [lang.intro] If I were to build a bridge, I would seriously consider what material to build it out of. Also, the design of the bridge would be heavily influenced by the choice of material and vice versa. Reason- able designs for stone bridges differ from reasonable designs for steel bridges, from read more..

  • Page - 736

    Section 24.2 Design and Programming Language 725 that must be understood and considered by a designer. In addition, generally available major libraries – such as matrix libraries, database interfaces, graphical user interface libraries, and con- currency support libraries – can strongly affect design choices. Fear of novelty sometimes leads to sub-optimal use of C++. So does read more..

  • Page - 737

    726 Design and Programming Chapter 24 The lack of language support for data abstraction implied by the decision to ignore classes will hurt. The inherent complexity will show up in the application somewhere, and if the system is implemented in an impoverished language, the code will not reflect the design directly. The pro- gram will have too many lines of source code, lack read more..

  • Page - 738

    Section 24.2.1 Ignoring Classes 727 However, some problems are best solved by writing a set of procedures. The point of an ‘‘object-oriented’’ approach to design is not that there should never be any nonmember functions in a program or that no part of a system may be procedure-oriented. Rather, the key point is to decou- ple different parts of a program to better reflect the read more..

  • Page - 739

    728 Design and Programming Chapter 24 and it is often safe to ignore type issues almost completely in the analysis stage and early design stages. However, classes and class hierarchies are very useful in the design. In particular, they allow us to be specific about concepts, allow us to be precise about their relationships, and help us reason about the concepts. As the read more..

  • Page - 740

    Section 24.2.3 Ignoring Static Type Checking 729 / / Example assuming dynamic type checking instead of static checking: S St ta ac ck k s s; / / Stack can hold pointers to objects of any type v vo oi id d f f() { s s.p pu us sh h(n ne ew w S Sa aa ab b9 90 00 0) ; s s.p pu us sh h(n ne ew w S Sa aa ab b3 37 7B B) ; s s.p po op p()->t read more..

  • Page - 741

    730 Design and Programming Chapter 24 c cl la as ss s C Ca ar r { / / ... v vo oi id d t tu ur rn n _ _r ri ig gh ht t() ; }; v vo oi id d f f(X X* p p) / / what type should X be? { p p->t tu ur rn n _ _r ri ig gh ht t() ; / / ... } Some languages (such as Smalltalk and CLOS) allow two types to be used interchangeably if they read more..

  • Page - 742

    Section 24.2.4 Avoiding Programming 731 in a tiny fraction of the time it would take to construct the same interface by writing traditional code. Similarly, database layouts and the code for accessing data according to such layouts can be generated from specifications that are far simpler than the code needed to express those operations directly in C++ or in any other read more..

  • Page - 743

    732 Design and Programming Chapter 24 be designed to combine the strengths of higher-level specifications and higher-level programming languages. To exclude one or the other is to sacrifice the interests of system builders to the inter- ests of tool providers. Successful large systems are multilevel and modular and evolve over time. Consequently, successful efforts to produce such read more..

  • Page - 744

    Section 24.3 Classes 733 The analysis of relationships between classes and within parts of a class is central to the design of a system: §24.3.2 Inheritance relationships §24.3.3 Containment relationships §24.3.5 Use relationships §24.2.4 Programmed-in relationships §24.3.7 Relationships within a class Because a C++ class is a type, classes and the relationships between classes receive read more..

  • Page - 745

    734 Design and Programming Chapter 24 [3] lumber and bricks; [4] floors, walls, and ceilings; and [5] rooms. As long as these levels of abstraction are kept separate, you can maintain a coherent view of the house. However, if you mix them, absurdities arise. For example, the statement, ‘‘My house con- sists of several thousand pounds of carbon, some complex polymers, about 5,000 read more..

  • Page - 746

    Section 24.3.2 Class Hierarchies 735 V Ve eh hi ic cl le e C Ca ar r E Em me er rg ge en nc cy y T Tr ru uc ck k P Po ol li ic ce e _ _c ca ar r A Am mb bu ul la an nc ce e F Fi ir re e _ _e en ng gi in ne e H Ho oo ok k _ _a an nd d _ _l la ad dd de er r .. Here, E Em me er rg ge en nc cy y represents the read more..

  • Page - 747

    736 Design and Programming Chapter 24 Class E Em me er rg ge en nc cy y is now simply used as a member in classes that might need to act as emergency vehicles: c cl la as ss s E Em me er rg ge en nc cy y { /* ... */ }; c cl la as ss s V Ve eh hi ic cl le e { p pr ro ot te ec ct te ed d: E Em me er rg ge en nc cy y* e ep read more..

  • Page - 748

    Section 24.3.2 Class Hierarchies 737 For people who consider traffic simulations esoteric, it might be worth pointing out that such tradeoffs between inheritance and membership almost invariably occur in a design. The scrollbar example in §24.3.3 is an equivalent example. 24.3.2.1 Dependencies within a Class Hierarchy [lang.internal] Naturally, a derived class depends on its base classes. It is read more..

  • Page - 749

    738 Design and Programming Chapter 24 The specification of the expected behavior of virtual functions is a major focus of class design. Choosing good names for classes and functions is important – and not always easy. Is a dependency on unknown (possibly yet unwritten) derived classes good or bad? Naturally, that depends on the intent of the programmer. If the intent is to read more..

  • Page - 750

    Section 24.3.3 Containment Relationships 739 If the value of the pointer is never changed, these alternatives are equivalent, except for efficiency issues and the way you write constructors and destructors: c cl la as ss s X X { p pu ub bl li ic c: X X(i in nt t) ; / / ... }; c cl la as ss s C C { X X a a; X X* p p; X X& r r; p pu ub bl li ic read more..

  • Page - 751

    740 Design and Programming Chapter 24 between representing a property of a class as a base class or representing it as a member. A need to override is an indication that the former is the better choice. Conversely, a need to be able to allow the property to be represented by a variety of types is an indication that the latter is the better choice. For example: c cl read more..

  • Page - 752

    Section 24.3.4 Containment and Inheritance 741 c cl la as ss s D D { / / a D contains a B p pu ub bl li ic c: B B b b; / / ... }; Alternatively, this is expressed by saying that membership is a has-a relationship. For given classes B B and D D, how do we choose between inheritance and membership? Consider an A Ai ir rp pl la an ne e and an E En ng read more..

  • Page - 753

    742 Design and Programming Chapter 24 c cl la as ss s D D2 2 : p pu ub bl li ic c B B { / / a D2 is a B p pu ub bl li ic c: v vo oi id d f f() ; / / overrides B::f() }; v vo oi id d h h2 2(D D2 2* p pd d) { B B* p pb b = p pd d; / / ok: implicit D2* to B* conversion p pb b->g g() ; / / calls B::g() p pd d->g g() read more..

  • Page - 754

    Section 24.3.4 Containment and Inheritance 743 publicly from an abstract base class that defines an interface and using private or protected deriva- tion from a concrete class to provide an implementation (§2.5.4, §12.3, §25.3). Because the inheri- tance implied in private and protected derivation is an implementation detail that is not reflected in the type of the derived class, read more..

  • Page - 755

    744 Design and Programming Chapter 24 That is, we are facing a tradeoff between expressing this aspect of the structure of the system in terms of declarations or in terms of code. The former increases the degree of static checking and the amount of information on which tools have to work. The latter postpones decisions to run time and allows changes to be made by read more..

  • Page - 756

    Section 24.3.4.2 Containment/Hierarchy Tradeoffs 745 around the way we passed an O Or ri ie en nt ta at ti io on n (§24.3.4.1). If we need to have W Wi in nd do ow w _ _w wi it th h _ _s sc cr ro ol ll lb ba ar r act as a scrollbar, we can add a conversion operator: W Wi in nd do ow w _ _w wi it th h _ _s sc cr ro ol ll lb ba ar read more..

  • Page - 757

    746 Design and Programming Chapter 24 c cl la as ss s Y Y; / / Y is the name of a class Y Y* p p; e ex xt te er rn n Y Y f f(c co on ns st t Y Y&) ; It is often important to distinguish between the dependencies of a class’ interface (the class declara- tion) and the dependencies of the class implementation (the class member definitions). In a read more..

  • Page - 758

    Section 24.3.6 Programmed-In Relationships 747 c cl la as ss s A A { B B* p p; / / delegation through p / / ... v vo oi id d f f() ; v vo oi id d f ff f() ; v vo oi id d g g() { p p->g g() ; } / / delegate g() v vo oi id d h h() { p p->h h() ; } / / delegate h() }; It is fairly obvious to a programmer what is going on here, read more..

  • Page - 759

    748 Design and Programming Chapter 24 v vo oi id d f f(R Ra at ti io on na al l r r, B Bi ig g _ _i in nt t i i) { g g(r r+i i) ; / / error, ambiguous: operator+(r,Rational(i)) or operator+(Big _int(r),i) ? g g(r r+R Ra at ti io on na al l(i i)) ; / / one explicit resolution g g(B Bi ig g _ _i in nt t(r r)+i i) ; / / another explicit read more..

  • Page - 760

    Section 24.3.7.1 Invariants 749 Thus, the purpose of initialization is to put an object into a state for which the invariant holds. Typically, this is done by a constructor. Each operation on a class can assume it will find the invariant true on entry and must leave the invariant true on exit. The destructor finally invalidates the invariant by destroying the object. For read more..

  • Page - 761

    750 Design and Programming Chapter 24 c ch ha ar r& S St tr ri in ng g: : o op pe er ra at to or r[](i in nt t i i) { c ch he ec ck k() ; / / check on entry i if f ( i i<0 0 || s sz z<=i i) t th hr ro ow w R Ra an ng ge e() ; / / do work c ch he ec ck k() ; / / check on exit r re et tu ur rn n p p[i i] ; read more..

  • Page - 762

    Section 24.3.7.2 Assertions 751 The alternative is to use an A As ss se er rt t() template that throws an exception rather than aborting so that assertions can be left in production code when that is desirable. Unfortunately, the standard library doesn’t provide an A As ss se er rt t(). However, it is trivially defined: t te em mp pl la at te e<c cl la as ss read more..

  • Page - 763

    752 Design and Programming Chapter 24 shipped code. This style of usage is most easily managed if the actual assertion is in two parts, with the first being an enabling condition (such as A AR RG G _ _C CH HE EC CK K) and the second being the asser- tion proper. If the enabling condition is a constant expression, the whole assertion will be compiled away when not read more..

  • Page - 764

    Section 24.3.7.2 Assertions 753 v vo oi id d g g(i in nt t* p p, e ex xc ce ep pt ti io on n e e) { A As ss se er rt t(!g g _ _c ch he ec ck k || p p!=0 0, e e) ; / / pointer is valid A As ss se er rt t(!g g _ _c ch he ec ck k || ( 0 0<*p p&&*p p<=g g _ _m ma ax x) , B Ba ad d _ _g g _ _a ar rg g(p p)) read more..

  • Page - 765

    754 Design and Programming Chapter 24 / / [first,last) is in increasing order: check a sample: A As ss se er rt t<F Fa ai il le ed d _ _s so or rt t>(N ND DE EB BU UG G || ( l la as st t-f fi ir rs st t<2 2 || (* f fi ir rs st t<=l la as st t[-1 1] && * f fi ir rs st t<=f fi ir rs st t[(l la as st t-f fi ir rs read more..

  • Page - 766

    Section 24.4 Components 755 24.4 Components [lang.component] The unit of design is a collection of classes, functions, etc., rather than an individual class. Such a collection, often called a library or a framework (§25.8), is also the unit of reuse (§23.5.1), mainte- nance, etc. C++ provides three mechanisms for expressing the notion of a set of facilities united by a logical criteria: [1] read more..

  • Page - 767

    756 Design and Programming Chapter 24 n na am me es sp pa ac ce e X X _ _i im mp pl l { / / facilities needed by X’s implementation u us si in ng g n na am me es sp pa ac ce e X X; / / ... } v vo oi id d X X: : f f() { u us si in ng g n na am me es sp pa ac ce e X X _ _i im mp pl l; / / dependent on declarations from X read more..

  • Page - 768

    Section 24.4 Components 757 The decision to nest or not depends on the aims of the design and the generality of the concepts involved. Both nesting and ‘‘non-nesting’’ are widely applicable techniques for expressing a design. The default should be to make a class as local as possible until a need to make it more gen- erally available is demonstrated. There is a nasty tendency read more..

  • Page - 769

    758 Design and Programming Chapter 24 This allows us to use a variety of unrelated iterators as long as they all provide f fi ir rs st t() and n ne ex xt t() with the right meanings and as long as we know the type of iterator for each call of p pr ri in nt t _ _a al ll l() at compile time. The standard library containers and algorithms are based on read more..

  • Page - 770

    Section 24.4.2 Interfaces and Implementations 759 – does not reveal implementation details to a user, – can be implemented in several ways, – is statically typed, – is expressed using application-level types, and – depends in limited and well-defined ways on other interfaces. Having noted the need for consistency across the classes that present the component’s interface to the read more..

  • Page - 771

    760 Design and Programming Chapter 24 management system, it might be wise not to depend too directly on them. In such cases, using a pointer or a reference member is often a better choice: c cl la as ss s Y Y; c cl la as ss s Z Z; c cl la as ss s X X { / / X accesses Y and Z through pointers and references only Y Y* a a; Z Z& b b; / / ... read more..

  • Page - 772

    Section 24.4.3 Fat Interfaces 761 24.4.3 Fat Interfaces [lang.fat] Ideally, an interface should offer only operations that make sense and that can be implemented well by every derived class implementing that interface. However, this is not always easy. Consider lists, arrays, associative arrays, trees, etc. As shown in §16.2.2, it is tempting and sometimes useful to provide a generalization of read more..

  • Page - 773

    762 Design and Programming Chapter 24 v vo oi id d f f() { L Li is st t _ _c co on nt ta ai in ne er r s sc c; V Ve ec ct to or r _ _c co on nt ta ai in ne er r v vc c; / / ... u us se er r(s sc c,v vc c) ; } v vo oi id d u us se er r(C Co on nt ta ai in ne er r& c c1 1, C Co on nt ta ai in ne er r& c read more..

  • Page - 774

    Section 24.4.3 Fat Interfaces 763 when the program is in the hands of users. The problem with this approach is that exhaustive test- ing is also hard and expensive. Consequently, fat interfaces are best avoided where run-time performance is at a premium, where strong guarantees about the correctness of code are required, and in general wherever there is a good alternative. The read more..

  • Page - 775

    764 Design and Programming Chapter 24 [27] Use templates for generic programming; §24.4.1. [28] Use templates to parameterize an algorithm by a policy; §24.4.1. [29] Use templates where compile-time type resolution is needed; §24.4.1. [30] Use class hierarchies where run-time type resolution is needed; §24.4.1. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright read more..

  • Page - 776

    _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 25 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Roles of Classes Some things better change ... but read more..

  • Page - 777

    766 Roles of Classes Chapter 25 these kinds of classes has a place in design and none is inherently better than the others for all uses. Much confusion in discussions of design and programming comes from people trying to use only one or two kinds of classes exclusively. This is usually done in the name of simplicity, yet it leads to contorted and unnatural uses of the read more..

  • Page - 778

    Section 25.2 Concrete Types 767 The name ‘‘concrete type’’ was chosen to contrast with the common term ‘‘abstract type.’’ The relationship between concrete and abstract types is discussed in §25.3. Concrete types cannot directly express commonality. For example, l li is st t and v ve ec ct to or r provide sim- ilar sets of operations and can be used interchangeably by some read more..

  • Page - 779

    768 Roles of Classes Chapter 25 The fundamental similarity between containers is exploited, and this in turn opens the possibility for further exploitation as done by the standard algorithms (Chapter 18). To use a concrete type well, the user must understand its particular details. There are (typically) no general properties that hold for all concrete types in a library that can read more..

  • Page - 780

    Section 25.2.1 Reuse of Concrete Types 769 c cl la as ss s D Da at te e2 2 { p pu ub bl li ic c: / / public interface, consisting primarily of virtual functions p pr ro ot te ec ct te ed d: / / other implementation details (possibly including some representation) p pr ri iv va at te e: / / representation and other implementation details }; To make writing read more..

  • Page - 781

    770 Roles of Classes Chapter 25 t te em mp pl la at te e<c cl la as ss s T T> c cl la as ss s S Se et t { p pu ub bl li ic c: v vi ir rt tu ua al l v vo oi id d i in ns se er rt t(T T*) = 0 0; v vi ir rt tu ua al l v vo oi id d r re em mo ov ve e(T T*) = 0 0; v vi ir rt tu ua al l i in nt t i is read more..

  • Page - 782

    Section 25.3 Abstract Types 771 introduced. All dependencies are contained in functions that explicitly use a class derived from S Se et t. In particular, assuming the conventional use of header files the programmer writing f f(S Se et t&) needs only include S Se et t.h h and not L Li is st t _ _s se et t.h h or V Ve ec ct to or r _ _s se et t.h h. read more..

  • Page - 783

    772 Roles of Classes Chapter 25 [3] Multiple interfaces. Using a single common base for a variety of classes leads to fat inter- faces (§24.4.3). Often, it is better to provide a new interface to a class used for new pur- poses (such as a S Se et t interface for a v ve ec ct to or r) rather than modify its interface to serve multiple purposes. Naturally, these read more..

  • Page - 784

    Section 25.4 Node Classes 773 v vo oi id d u us se er r() { / / ... C Ca ar r* p p = n ne ew w C Ca ar r(3 3,e ec co on no om my y,1 15 50 00 0,6 60 0) ; d dr ri iv ve e(p p,b bs s _ _h ho om me e,M MH H) ; / / enter into simulated traffic pattern / / ... } A node class usually needs constructors and often a nontrivial constructor. read more..

  • Page - 785

    774 Roles of Classes Chapter 25 [5] can be understood only in the context of its base classes; [6] can be used as a base for further derivation; and [7] can be used to create objects. Not every node class will conform to all of points 1, 2, 6, and 7, but most do. A class that does not conform to point 6 resembles a concrete type and could be called a read more..

  • Page - 786

    Section 25.4.1 Changing Interfaces 775 c cl la as ss s I Io o _ _o ob bj j { p pu ub bl li ic c: v vi ir rt tu ua al l I Io o _ _o ob bj j* c cl lo on ne e() c co on ns st t = 0 0; / / polymorphic v vi ir rt tu ua al l ~ I Io o _ _o ob bj j() {} }; The critical function in the object I/O system is g ge et t _ _o ob bj read more..

  • Page - 787

    776 Roles of Classes Chapter 25 The I Io o _ _c ci ir rc cl le e(i is st tr re ea am m&) constructor initializes an object with data from its i is st tr re ea am m argument. The n ne ew w _ _c ci ir rc cl le e() function is the one put into the i io o _ _m ma ap p to make the class known to the object I/O system. For example: i io o read more..

  • Page - 788

    Section 25.5 Actions 777 (§18.4), and so are the manipulators used with i io os st tr re ea am ms (§21.4.6). In the former case, the actual action is performed by the application operator, and in the latter case, by the << or >> operators. In the case of F Fo or rm m (§21.4.6.3) and M Ma at tr ri ix x (§22.4.7), compositor classes were used to delay execu- tion until read more..

  • Page - 789

    778 Roles of Classes Chapter 25 This is a powerful technique that should be treated with some care by people with a background in functional decomposition. If too many classes start looking like A Ac ct ti io on n, the overall design of the system may have deteriorated into something unduly functional. Finally, a class can encode an operation for execution on a remote read more..

  • Page - 790

    Section 25.6 Interface Classes 779 c cl la as ss s C Co ow wb bo oy y _ _w wi in nd do ow w : p pu ub bl li ic c C Co ow wb bo oy y, p pu ub bl li ic c W Wi in nd do ow w { / / ... }; A C Co ow wb bo oy y _ _w wi in nd do ow w represents the animation of a cowboy in the game and handles the user/player’s interactions with read more..

  • Page - 791

    780 Roles of Classes Chapter 25 For each use of an interface class, one could imagine a special-purpose language extension that could perform the desired adjustment a little bit more efficiently or a little more elegantly. How- ever, each use of an interface class is infrequent and supporting them all with specialized language constructs would impose a prohibitive burden of read more..

  • Page - 792

    Section 25.6.1 Adjusting Interfaces 781 A V Ve ec ct to or r can be used like this: v vo oi id d g g() { V Ve ec ct to or r v v(1 1,1 10 0) ; / / range [1:10] f fo or r ( i in nt t i i = 1 1; i i<=1 10 0; i i++) { v v[i i] = 7 7; / / ... } } This imposes no overhead compared to the previous example. Clearly, the V Ve ec ct to read more..

  • Page - 793

    782 Roles of Classes Chapter 25 25.7 Handle Classes [role.handle] An abstract type provides an effective separation between an interface and its implementations. However, as used in §25.3 the connection between an interface provided by an abstract type and its implementation provided by a concrete type is permanent. For example, it is not possible to rebind an abstract iterator from one source – read more..

  • Page - 794

    Section 25.7 Handle Classes 783 v vo oi id d f f(S Se et t _ _h ha an nd dl le e<i in nt t> s s) { f fo or r ( i in nt t* p p = s s->f fi ir rs st t() ; p p; p p = s s->n ne ex xt t()) { / / ... } } v vo oi id d u us se er r() { S Se et t _ _h ha an nd dl le e<i in nt t> s sl l(n ne ew w L Li is read more..

  • Page - 795

    784 Roles of Classes Chapter 25 v vo oi id d f f1 1(H Ha an nd dl le e<S Se et t>) ; H Ha an nd dl le e<S Se et t> f f2 2() { H Ha an nd dl le e<S Se et t> h h(n ne ew w L Li is st t _ _s se et t<i in nt t>) ; / / ... r re et tu ur rn n h h; } v vo oi id d g g() { H Ha an nd dl le e<S Se et read more..

  • Page - 796

    Section 25.7 Handle Classes 785 As written, H Ha an nd dl le e doesn’t deal with inheritance. To get a class that acts like a genuine use- counted pointer, H Ha an nd dl le e needs to be combined with P Pt tr r from §13.6.3.1 (see §25.10[2]). A handle that provides an interface that is close to identical to the class for which it is a handle is often called read more..

  • Page - 797

    786 Roles of Classes Chapter 25 An advantage of the elaborate definition of all operations on the handle over the overloading of -> style of handles is that it is possible to derive from class S Se et t _ _c co on nt tr ro ol ll le er r. Unfortunately, some of the benefits of being a handle are compromised if data members are added in the derived class. In read more..

  • Page - 798

    Section 25.8 Application Frameworks 787 i in nt t m ma ai in n _ _l lo oo op p(F Fi il lt te er r* p p) { f fo or r(;;) { t tr ry y { p p->s st ta ar rt t() ; w wh hi il le e ( p p->r re ea ad d()) { p p->c co om mp pu ut te e() ; p p->w wr ri it te e() ; } r re et tu ur rn n p p->r re es su ul lt t() ; read more..

  • Page - 799

    788 Roles of Classes Chapter 25 25.9 Advice [role.advice] [1] Make conscious decisions about how a class is to be used (both as a designer and as a user); §25.1. [2] Be aware of the tradeoffs involved among the different kinds of classes; §25.1. [3] Use concrete types to represent simple independent concepts; §25.2. [4] Use concrete types to represent concepts where read more..

  • Page - 800

    Section 25.10 Exercises 789 an input stream and produces a list of (word,count) pairs in frequency order as output. 7. ( ∗1.5) Write a R Ra an ng ge e template that takes both the range and the element type as template parameters. 8. ( ∗1) Write a R Ra an ng ge e template that takes the range as constructor arguments. 9. ( ∗2) Write a simple string class that read more..

  • Page - 801

    790 Roles of Classes Chapter 25 The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved. read more..

  • Page - 802

    Appendices and Index These Appendices provide the C++ grammar, a discussion of compatibility issues that arise between C++ and C and between Standard C++ and prestandard versions of C++, and a variety of language-technical details. The index is extensive and considered an integral part of the book. Chapters A Grammar B Compatibility C Technicalities I Index The C++ Programming Language, read more..

  • Page - 803

    792 Appendices Appendices The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved. read more..

  • Page - 804

    _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Appendix A _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Grammar There is no worse danger for a teacher read more..

  • Page - 805

    794 Grammar Appendix A namespace-name: original-namespace-name namespace-alias original-namespace-name: identifier namespace-alias: identifier class-name: identifier template-id enum-name: identifier template-name: identifier Note that a typedef-name naming a class is also a class-name. Unless an identifier is explicitly declared to name a type, it is assumed to name something that is not a type (see §C.13.5). read more..

  • Page - 806

    Section A.3 Lexical Conventions 795 universal-character-name: \u hex-quad \U hex-quad hex-quad preprocessing-token: header-name identifier pp-number character-literal string-literal preprocessing-op-or-punc each non-white-space character that cannot be one of the above token: identifier keyword literal operator punctuator header-name: < h-char-sequence> " q-char-sequence" h-char-sequence: h-char h-char-sequence h-char read more..

  • Page - 807

    796 Grammar Appendix A nondigit: one of universal-character-name _ a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z digit: one of 0 1 2 3 4 5 6 7 8 9 preprocessing-op-or-punc: one of { } [ ] # ## ( ) <: :> <% %> %:%: %: ; : ? :: . .* + - * / read more..

  • Page - 808

    Section A.3 Lexical Conventions 797 integer-suffix: unsigned-suffix long-suffix opt long-suffix unsigned-suffix opt unsigned-suffix: one of u U long-suffix: one of l L character-literal: ’ c-char-sequence’ L’ c-char-sequence’ c-char-sequence: c-char c-char-sequence c-char c-char: any member of the source character set except the single-quote, backslash, or new-line character escape-sequence universal-character-name read more..

  • Page - 809

    798 Grammar Appendix A digit-sequence: digit digit-sequence digit floating-suffix: one of f l F L string-literal: " s-char-sequence opt" L" s-char-sequence opt" s-char-sequence: s-char s-char-sequence s-char s-char: any member of the source character set except double-quote, backslash , or new-line escape-sequence universal-character-name boolean-literal: false true A.4 Programs A program is a read more..

  • Page - 810

    Section A.5 Expressions 799 id-expression: unqualified-id qualified-id unqualified-id: identifier operator-function-id conversion-function-id ~ class-name template-id qualified-id: nested-name-specifier template opt unqualified-id nested-name-specifier: class-or-namespace-name :: nested-name-specifier opt class-or-namespace-name :: template nested-name-specifier class-or-namespace-name: class-name namespace-name postfix-expression: primary-expression read more..

  • Page - 811

    800 Grammar Appendix A unary-expression: postfix-expression ++ cast-expression -- cast-expression unary-operator cast-expression sizeof unary-expression sizeof ( type-id ) new-expression delete-expression unary-operator: one of * & + - ! ~ new-expression: :: opt new new-placement opt new-type-id new-initializer opt :: opt new new-placement opt ( type-id ) new-initializer opt new-placement: ( expression-list ) new-type-id: read more..

  • Page - 812

    Section A.5 Expressions 801 additive-expression: multiplicative-expression additive-expression + multiplicative-expression additive-expression - multiplicative-expression shift-expression: additive-expression shift-expression << additive-expression shift-expression >> additive-expression relational-expression: shift-expression relational-expression < shift-expression relational-expression > shift-expression relational-expression <= read more..

  • Page - 813

    802 Grammar Appendix A expression: assignment-expression expression , assignment-expression constant-expression: conditional-expression Grammar ambiguities arise from the similarity between function style casts and declarations. For example: i in nt t x x; v vo oi id d f f() { c ch ha ar r(x x) ; / / conversion of x to char or declaration of a char called x? } All such ambiguities read more..

  • Page - 814

    Section A.6 Statements 803 labeled-statement: identifier : statement case constant-expression : statement default : statement expression-statement: expression opt ; compound-statement: { statement-seq opt } statement-seq: statement statement-seq statement selection-statement: if ( condition ) statement if ( condition ) statement else statement switch ( condition ) statement condition: expression type-specifier-seq declarator = read more..

  • Page - 815

    804 Grammar Appendix A declaration: block-declaration function-definition template-declaration explicit-instantiation explicit-specialization linkage-specification namespace-definition block-declaration: simple-declaration asm-definition namespace-alias-definition using-declaration using-directive simple-declaration: decl-specifier-seq opt init-declarator-list opt ; decl-specifier: storage-class-specifier type-specifier function-specifier friend typedef read more..

  • Page - 816

    Section A.7 Declarations 805 simple-type-specifier: :: opt nested-name-specifier opt type-name :: opt nested-name-specifier template opt template-id char wchar _t bool short int long signed unsigned float double void type-name: class-name enum-name typedef-name elaborated-type-specifier: class-key :: opt nested-name-specifier opt identifier enum :: opt nested-name-specifier opt identifier typename :: opt nested-name-specifier read more..

  • Page - 817

    806 Grammar Appendix A named-namespace-definition: original-namespace-definition extension-namespace-definition original-namespace-definition: namespace identifier { namespace-body } extension-namespace-definition: namespace original-namespace-name { namespace-body } unnamed-namespace-definition: namespace { namespace-body } namespace-body: declaration-seq opt namespace-alias: identifier namespace-alias-definition: namespace identifier = read more..

  • Page - 818

    Section A.7.1 Declarators 807 A.7.1 Declarators See §4.9.1, Chapter 5 (pointers and arrays), §7.7 (pointers to functions), and §15.5 (pointers to members). init-declarator-list: init-declarator init-declarator-list , init-declarator init-declarator: declarator initializer opt declarator: direct-declarator ptr-operator declarator direct-declarator: declarator-id direct-declarator ( parameter-declaration-clause ) cv-qualifier-seq opt read more..

  • Page - 819

    808 Grammar Appendix A parameter-declaration-clause: parameter-declaration-list opt ... opt parameter-declaration-list , ... parameter-declaration-list: parameter-declaration parameter-declaration-list , parameter-declaration parameter-declaration: decl-specifier-seq declarator decl-specifier-seq declarator = assignment-expression decl-specifier-seq abstract-declarator opt decl-specifier-seq abstract-declarator opt = assignment-expression read more..

  • Page - 820

    Section A.8 Classes 809 class-head: class-key identifier opt base-clause opt class-key nested-name-specifier identifier base-clause opt class-key nested-name-specifier template template-id base-clause opt class-key: class struct union member-specification: member-declaration member-specification opt access-specifier : member-specification opt member-declaration: decl-specifier-seq opt member-declarator-list opt ; function-definition ; opt read more..

  • Page - 821

    810 Grammar Appendix A base-specifier-list: base-specifier base-specifier-list , base-specifier base-specifier: :: opt nested-name-specifier opt class-name virtual access-specifier opt :: opt nested-name-specifier opt class-name access-specifier virtual opt :: opt nested-name-specifier opt class-name access-specifier: private protected public A.8.2 Special Member Functions See §11.4 (conversion operators), §10.4.6 (class member read more..

  • Page - 822

    Section A.8.3 Overloading 811 operator: one of new delete new[] delete[] + - * / % ^ & | ~ ! = < > += -= *= /= %= ^= &= |= << >> >>= <<= == != <= >= && || ++ -- , ->* -> () [] A.9 Templates Templates are explained in Chapter 13 and §C.13. template-declaration: export opt template < template-parameter-list > declaration read more..

  • Page - 823

    812 Grammar Appendix A v vo oi id d h h() { f f<1 1>(0 0) ; / / ambiguity: ((f) <1) > (0) or (f <1>)(0) ? / / resolution: f <1> is called with argument 0 } The resolution is simple and effective: if f f is a template name, f f< is the beginning of a qualified template name and the subsequent tokens must be interpreted based on that; read more..

  • Page - 824

    Section A.10 Exception Handling 813 A.11 Preprocessing Directives The preprocessor is a relatively unsophisticated macro processor that works primarily on lexical tokens rather than individual characters. In addition to the ability to define and use macros (§7.8), the preprocessor provides mechanisms for including text files and standard headers (§9.2.1) and conditional compilation based on read more..

  • Page - 825

    814 Grammar Appendix A control-line: # include pp-tokens new-line # define identifier replacement-list new-line # define identifier lparen identifier-list opt ) replacement-list new-line # undef identifier new-line # line pp-tokens new-line # error pp-tokens opt new-line # pragma pp-tokens opt new-line # new-line lparen: the left-parenthesis character without preceding white-space replacement-list: pp-tokens opt read more..

  • Page - 826

    _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Appendix B _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Compatibility You go ahead and follow your customs, read more..

  • Page - 827

    816 Compatibility Appendix B B.2 C/C++ Compatibility With minor exceptions, C++ is a superset of C (meaning C89, defined by ISO/IEC 9899:1990). Most differences stem from C++’s greater emphasis on type checking. Well-written C programs tend to be C++ programs as well. A compiler can diagnose every difference between C++ and C. B.2.1 ‘‘Silent’’ Differences With a few exceptions, read more..

  • Page - 828

    Section B.2.2 C Code That Is Not C++ 817 options to enforce it, C code conforms to the C++ rule. Where undeclared functions are called, you have to know the functions and the rules for C pretty well to know whether you have made a mis- take or introduced a portability problem. For example, the previous m ma ai in n() contains at least two errors as a C program. read more..

  • Page - 829

    818 Compatibility Appendix B In C, some of the C++ keywords are macros defined in standard headers: _ ______________________________________________________________ C++ Keywords That Are C Macros _ ______________________________________________________________ _ ______________________________________________________________ a an nd d a an nd d _ _e eq q b bi it ta an nd d b bi it to or r b bo read more..

  • Page - 830

    Section B.2.3 Deprecated Features 819 / / file1: s st ta at ti ic c i in nt t g gl lo ob b; / / file2: s st ta at ti ic c i in nt t g gl lo ob b; This program genuinely has two integers called g gl lo ob b. Each g gl lo ob b is used exclusively by functions defined in its translation unit. The use of s st ta at ti ic c to indicate read more..

  • Page - 831

    820 Compatibility Appendix B [5] v vi ir rt tu ua al l functions and abstract classes (§12.2.6, §12.3) [6] Public/protected/private access control (§10.2.2, §15.3, §C.11) [7] f fr ri ie en nd ds (§11.5) [8] Pointers to members (§15.5, §C.12) [9] s st ta at ti ic c members (§10.2.4) [10] m mu ut ta ab bl le e members (§10.2.7.2) [11] Operator overloading (Chapter 11) read more..

  • Page - 832

    Section B.3 Coping with Older C++ Implementations 821 doesn’t provide at least some of these features. I added multiple inheritance, templates, and excep- tions to the definition of C++ in 1989. However, early support for templates and exceptions was uneven and often poor. If you find problems with templates or exceptions in an older implementa- tion, consider an immediate read more..

  • Page - 833

    822 Compatibility Appendix B For example, if declarations that we need are provided in different headers in different systems, we may choose to # i in nc cl lu ud de e an application specific header that in turn # i in nc cl lu ud de es the appropriate header(s) for each system. Similarly, if some functionality is provided in slightly different forms on different read more..

  • Page - 834

    Section B.3.3 Namespaces 823 c cl la as ss s j jo oe e _ _s st tr ri in ng g; / / Joe’s string e en nu um m j jo oe e _ _b bo oo ol l { j jo oe e _ _f fa al ls se e, j jo oe e _ _t tr ru ue e }; / / Joe’s bool Be careful when choosing a prefix. Existing C and C++ libraries are littered with such prefixes. B.3.4 Allocation Errors In read more..

  • Page - 835

    824 Compatibility Appendix B functions (§C.13.9.1). The solution is to place the definition of the member functions after the class declaration. For example, rather than t te em mp pl la at te e<c cl la as ss s T T> c cl la as ss s C Co on nt ta ai in ne er r { / / ... p pu ub bl li ic c: v vo oi id d s so or rt t() { /* use < */ read more..

  • Page - 836

    Section B.3.6 For-Statement Initializers 825 B.3.6 For-Statement Initializers Consider: v vo oi id d f f(v ve ec ct to or r<c ch ha ar r>& v v, i in nt t m m) { f fo or r ( i in nt t i i= 0 0; i i<v v.s si iz ze e() && i i<=m m; ++ i i) c co ou ut t << v v[i i] ; i if f ( i i == m m) { / / error: i referred read more..

  • Page - 837

    826 Compatibility Appendix B [11] A facility defined in namespace s st td d is defined in a header without a suffix (e.g. s st td d: : c co ou ut t is declared in < i io os st tr re ea am m>). Older implementations have standard library facilities in the global namespace and declared in headers with a . h h suffix (e.g. : : c co ou ut t declared read more..

  • Page - 838

    _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Appendix C _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Technicalities Deep in the fundamental heart of mind read more..

  • Page - 839

    828 Technicalities Appendix C or bad; it simply says what a programmer can and cannot rely on from an implementation. One can write perfectly awful standard-conforming programs, and most real-world programs rely on fea- tures not covered by the standard. Many important things are deemed implementation-defined by the standard. This means that each implementation must provide a specific, read more..

  • Page - 840

    Section C.3 Character Sets 829 C.3 Character Sets The examples in this book are written using the U.S. variant of the international 7-bit character set ISO 646-1983 called ASCII (ANSI3.4-1968). This can cause three problems for people who use C++ in an environment with a different character set: [1] ASCII contains punctuation characters and operator symbols – such as ] , { , read more..

  • Page - 841

    830 Technicalities Appendix C C.3.2 Escape Characters 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 read more..

  • Page - 842

    Section C.3.3 Large Character Sets 831 C.3.3 Large Character Sets A C++ program may be written and presented to the user in character sets that are much richer than the 127 character ASCII set. Where an implementation supports larger character sets, identifiers, comments, character constants, and strings may contain characters such as å , β, and Γ. However, to be portable the read more..

  • Page - 843

    832 Technicalities Appendix C v vo oi id d f f(c ch ha ar r c c, s si ig gn ne ed d c ch ha ar r s sc c, u un ns si ig gn ne ed d c ch ha ar r u uc c) { c ch ha ar r* p pc c = & u uc c; / / error: no pointer conversion s si ig gn ne ed d c ch ha ar r* p ps sc c = p pc c; / / error: no pointer conversion u un read more..

  • Page - 844

    Section C.5 Constant Expressions 833 C.5 Constant Expressions In places such as array bounds (§5.2), case labels (§6.3.2), and initializers for enumerators (§4.8), C++ requires a constant expression. A constant expression evaluates to an integral or enumeration constant. Such an expression is composed of literals (§4.3.1, §4.4.1, §4.5.1), enumerators (§4.8), and c co on ns st ts initialized read more..

  • Page - 845

    834 Technicalities Appendix C v vo oi id d f f(d do ou ub bl le e d d) { c ch ha ar r c c = d 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. A compiler can warn about many questionable conversions. Fortu- nately, many read more..

  • Page - 846

    Section C.6.2.3 Pointer and Reference Conversions 835 A constant expression (§C.5) that evaluates to 0 0 can be implicitly converted to any pointer or pointer to member type (§5.1.1). For example: i in nt t* p p = ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !!!!!! !!!!! !!!! 1 1; A T T* can be implicitly converted to a c co on ns st t T T* read more..

  • Page - 847

    836 Technicalities Appendix C c cl la as ss s c ch he ec ck k _ _f fa ai il le ed d { }; c ch ha ar r c ch he ec ck ke ed d(i in nt t i i) { c ch ha ar r c c = i i; / / warning: not portable (§C.6.2.1) i if f ( i i != c c) t th hr ro ow w c ch he ec ck k _ _f fa ai il le ed d() ; r re et tu ur rn n c c; } v read more..

  • Page - 848

    Section C.7.1 Vectors 837 v vo oi id d i in ni it t _ _m m() { m m.r re es si iz ze e(3 3) ; / / m now holds 3 empty vectors f fo or r ( i in nt t i i = 0 0; i i<m m.s si iz ze e() ; i i++) { m m[i i].r re es si iz ze e(5 5) ; / / now each of m’s vectors holds 5 ints f fo or r ( i in nt t j j = 0 0; j j<m read more..

  • Page - 849

    838 Technicalities Appendix C i in nt t m ma a[3 3][5 5] ; / / 3 arrays with 5 ints each For arrays, the dimensions must be given as part of the definition. We can initialize m ma a like this: v vo oi id d i in ni it t _ _m ma a() { f fo or r ( i in nt t i i = 0 0; i i<3 3; i i++) { f fo or r ( i in nt t j j = 0 0; j read more..

  • Page - 850

    Section C.7.3 Passing Multidimensional Arrays 839 A matrix represented as a multidimensional array is passed as a pointer (rather than copied; §5.3). The first dimension of an array is irrelevant to the problem of finding the location of an element; it simply states how many elements (here 3 3) of the appropriate type (here i in nt t[5 5]) are present. For example, look read more..

  • Page - 851

    840 Technicalities Appendix C Note the use of & v v[0 0][0 0] for the last call; v v[0 0] would do because it is equivalent, but v v would be a type error. This kind of subtle and messy code is best hidden. If you must deal directly with mul- tidimensional arrays, consider encapsulating the code relying on it. In that way, you might ease the task of the next read more..

  • Page - 852

    Section C.8.1 Fields 841 v vo oi id d p pa ar rt t _ _o of f _ _V VM M _ _s sy ys st te em m(P PP PN N* p p) { / / ... i if f ( p p->d di ir rt ty y) { / / contents changed / / copy to disc p p->d di ir rt ty y = 0 0; } / / ... } Surprisingly, using fields to pack several variables into a single byte does not necessarily save read more..

  • Page - 853

    842 Technicalities Appendix C s st tr ru uc ct t E En nt tr ry y { c ch ha ar r* n na am me e; T Ty yp pe e t t; V Va al lu ue e v v; / / use v.s if t==S; use v.i if t==I }; v vo oi id d f f(E En nt tr ry y* p p) { i if f ( p p->t t == S S) c co ou ut t << p p->v v.s s; / / ... } Unfortunately, the introduction read more..

  • Page - 854

    Section C.8.2 Unions 843 i in nt t* c ch he ea at t(i in nt t i i) { F Fu ud dg ge e a a; a a.i i = i i; r re et tu ur rn n a a.p p; / / bad use } This is not really a conversion at all. On some machines, an i in nt t and an i in nt t* do not occupy the same amount of space, while on others, no integer can have an odd address. read more..

  • Page - 855

    844 Technicalities Appendix C store (also called dynamic memory or the heap) grows throughout the lifetime of a program because no memory is ever returned to the operating system for use by other programs. As far as the programmer is concerned, automatic and static storage are used in simple, obvious, and implicit ways. The interesting question is how to manage the free store. read more..

  • Page - 856

    Section C.9.1.1 Disguised Pointers 845 / / point #1: no pointer to the int exists here p p = r re ei in nt te er rp pr re et t _ _c ca as st t<i in nt t*>(i i1 1|i i2 2) ; / / now the int is referenced again } Often, pointers stored as non-pointers in a program are called ‘‘disguised pointers.’’ In particular, the pointer originally held in p p read more..

  • Page - 857

    846 Technicalities Appendix C C.9.1.3 Destructors When an object is about to be recycled by a garbage collector, two alternatives exist: [1] Call the destructor (if any) for the object. [2] Treat the object as raw memory (don’t call its destructor). By default, a garbage collector should choose option (2) because objects created using n ne ew w and never d de el le et te read more..

  • Page - 858

    Section C.10 Namespaces 847 C.10 Namespaces This section presents minor points about namespaces that look like technicalities, yet frequently surface in discussions and in real code. C.10.1 Convenience vs. Safety A using-declaration adds a name to a local scope. A using-directive does not; it simply renders names accessible in the scope in which they were declared. For example: n na read more..

  • Page - 859

    848 Technicalities Appendix C whereas X X: : k k means ‘‘the k k declared in namespace X X and namespaces mentioned in u us si in ng g- d di ir re ec ct ti iv ve es in X X’’ (§8.2.8). I hope to see a radical decrease in the use of global names in new programs using namespaces compared to traditional C and C++ programs. The rules for namespaces were read more..

  • Page - 860

    Section C.10.2 Nesting of Namespaces 849 C.10.3 Namespaces and Classes A namespace is a named scope. A class is a type defined by a named scope that describes how objects of that type can be created and used. Thus, a namespace is a simpler concept than a class and ideally a class would be defined as a namespace with a few extra facilities included. This is almost the read more..

  • Page - 861

    850 Technicalities Appendix C v vo oi id d Y Y: : m md de er ri iv ve ed d() { p pr ri iv v = 1 1; / / error: priv is private p pr ro ot t = 2 2; / / ok: prot is protected and mderived() is a member of the derived class Y p pu ub bl l = 3 3; / / ok: publ is public } A global function can access only the public members: v vo oi id d f read more..

  • Page - 862

    Section C.11.2 Access to Base Classes 851 v vo oi id d Z Z2 2: : f f(Y Y1 1* p py y1 1, Y Y2 2* p py y2 2, Y Y3 3* p py y3 3) { X X* p px x = p py y1 1; / / ok: X is a public base class of Y1 p py y1 1->a a = 7 7; / / ok p px x = p py y2 2; / / ok: X is a protected base of Y2, and Z2 is derived from Y2 p py y2 read more..

  • Page - 863

    852 Technicalities Appendix C i in nt t g g(I In nn ne er r* p p) ; }; v vo oi id d O Ou ut te er r: : I In nn ne er r: : f f(O Ou ut te er r* p p, i in nt t v v) { p p->i i = v v; / / error: Outer::i is private p p->i i2 2 = v v; / / ok: Outer::i2 is public } i in nt t O Ou ut te er r: : g g(I In nn ne er r* p read more..

  • Page - 864

    Section C.11.4 Friendship 853 c cl la as ss s C C { v vo oi id d f f(A A* p p) { p p->a a++; / / error: C is not a friend of A, despite being a friend of a friend of A } }; c cl la as ss s D D : p pu ub bl li ic c B B { v vo oi id d f f(A A* p p) { p p->a a++; / / error: D is not a friend of A, despite being derived read more..

  • Page - 865

    854 Technicalities Appendix C C.13 Templates A class template specifies how a class can be generated given a suitable set of template arguments. Similarly, a function template specifies how a function can be generated given a suitable set of tem- plate arguments. Thus, a template can be used to generate types and executable code. With this expressive power comes some complexity. read more..

  • Page - 866

    Section C.13.2 Friends 855 t te em mp pl la at te e<c cl la as ss s T T> c cl la as ss s M Ma at th h _ _c co on nt ta ai in ne er r : p pu ub bl li ic c B Ba as si ic c _ _o op ps s< M Ma at th h _ _c co on nt ta ai in ne er r<T T> > { / / ... }; Like a member, a friend declared within a template is read more..

  • Page - 867

    856 Technicalities Appendix C T T c co on ns st t T T v vo ol la at ti il le e T T T T* T T& T T[c co on ns st ta an nt t _ _e ex xp pr re es ss si io on n] t ty yp pe e[I I] c cl la as ss s _ _t te em mp pl la at te e _ _n na am me e<T T> c cl la as ss s _ _t te em mp pl la at te e _ _n na am me read more..

  • Page - 868

    Section C.13.5 Typename and Template 857 t te em mp pl la at te e<c cl la as ss s T T> c cl la as ss s l li is st t { c cl la as ss s l li in nk k { / / ... }; p pu ub bl li ic c: t ty yp pe ed de ef f T T v va al lu ue e _ _t ty yp pe e; t ty yp pe ed de ef f l li in nk k* i it te er ra at to or r; read more..

  • Page - 869

    858 Technicalities Appendix C The resolution is simple: unless otherwise stated, an identifier is assumed to refer to something that is not a type or a template. If we want to state that something should be treated as a type, we can do so using the t ty yp pe en na am me e keyword: t te em mp pl la at te e<c cl la as ss s C C> v vo oi id d f read more..

  • Page - 870

    Section C.13.7 Instantiation 859 C.13.7 Instantiation Given a template definition and a use of that template, it is the implementation’s job to generate correct code. From a class template and a set of template arguments, the compiler needs to gener- ate the definition of a class and the definitions of those of its member functions that were used. From a template function, a read more..

  • Page - 871

    860 Technicalities Appendix C Operations with conventional names and semantics, such as + , * , [] , and s so or rt t(), are another source of nonlocal name use in a template definition. Consider: # i in nc cl lu ud de e<v ve ec ct to or r> b bo oo ol l t tr ra ac ci in ng g; / / ... t te em mp pl la at te e<c cl la as ss s T T> T read more..

  • Page - 872

    Section C.13.8.1 Dependent Names 861 [2] Names that don’t depend on a template argument. Such names are bound at the point of definition of the template (§C.13.8.2). In the s su um m() example, the template v ve ec ct to or r is defined in the standard header < v ve ec ct to or r> and the Boolean t tr ra ac ci in ng g is in scope when the defi- read more..

  • Page - 873

    862 Technicalities Appendix C t te em mp pl la at te e<c cl la as ss s T T> T T f f(T T a a) { x x++; / / ok y y++; / / error: no y in scope, and y doesn’t depend on T r re et tu ur rn n a a; } i in nt t y y; i in nt t z z = f f(2 2) ; If a declaration is found, that declaration is used even if a ‘‘better’’ declaration read more..

  • Page - 874

    Section C.13.8.3 Point of Instantiation Binding 863 C.13.8.3 Point of Instantiation Binding Each use of a template for a given set of template arguments defines a point of instantiation. That point is in the nearest global or namespace scope enclosing its use, just before the declaration that contains that use. For example: t te em mp pl la at te e<c cl la as ss s T read more..

  • Page - 875

    864 Technicalities Appendix C Note that a template used several times with the same set of template arguments has several points of instantiation. If the bindings of independent names differ, the program is illegal. How- ever, this is a difficult error for an implementation to detect, especially if the points of instantiation are in different translation units. It is best to read more..

  • Page - 876

    Section C.13.8.4 Templates and Namespaces 865 n na am me es sp pa ac ce e N N { c cl la as ss s A A { /* ... */ }; c ch ha ar r f f(A A,i in nt t) ; } t te em mp pl la at te e<c cl la as ss s T T, c cl la as ss s T T2 2> c ch ha ar r g g(T T t t, T T2 2 t t2 2) { r re et tu ur rn n f f(t t,t t2 2) ; read more..

  • Page - 877

    866 Technicalities Appendix C t te em mp pl la at te e<c cl la as ss s T T> c cl la as ss s L Li in nk k { L Li in nk k* s su uc c; / / ok: no definition of Link needed (yet) / / ... }; L Li in nk k<i in nt t>* p pl l; / / no instantiation of Link <int> needed L Li in nk k<i in nt t> l ln nk k; / / now we read more..

  • Page - 878

    Section C.13.10 Explicit Instantiation 867 As in template function calls, the template arguments that can be deduced from the function argu- ments can be omitted (§13.3.1). For example: t te em mp pl la at te e i in nt t c co on nv ve er rt t<i in nt t,d do ou ub bl le e>(d do ou ub bl le e) ; / / ok (redundant) t te em mp pl la at te e i read more..

  • Page - 879

    868 Technicalities Appendix C [13] Use fields to represent externally-imposed layouts; §C.8.1. [14] Be aware of the tradeoffs between different styles of memory management; §C.9. [15] Don’t pollute the global namespace; §C.10.1. [16] Where a scope (module) rather than a type is needed, prefer a n na am me es sp pa ac ce e over a c cl la as ss s; §C.10.3. [17] read more..

  • Page - 880

    _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Appendix D _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Locales When in Rome, do as the Romans do. – read more..

  • Page - 881

    870 Locales Appendix D The discussion of locales and facets is organized like this: §D.1 introduces the basic ideas for representing cultural differences using locales. §D.2 presents the l lo oc ca al le e class. §D.3 presents the f fa ac ce et t class. §D.4 gives an overview of the standard f fa ac ce et ts and presents details of each: §D.4.1 String comparison §D.4.2 read more..

  • Page - 882

    Section D.1.1 Programming Cultural Differences 871 creating a class hierarchy (§12.2.4). However, the information in a D Da at te e is independent of the way we want to look at it. Consequently, we don’t want a hierarchy of D Da at te e types: for example, U US S _ _d da at te e, U UK K _ _d da at te e, and J JP P _ _d da at te e. Instead, we read more..

  • Page - 883

    872 Locales Appendix D Given streams, A Ap pr r 1 12 2, 1 19 99 99 9 1 10 00 00 0.3 3 A Ap pr r 1 13 3, 1 19 99 99 9 3 34 45 5.4 45 5 A Ap pr r 1 14 4, 1 19 99 99 9 9 96 68 88 8.3 32 21 1 ... 3 3 j ju ui il ll le et t 1 19 95 50 0 1 10 0,3 3 3 3 j ju ui il ll le et t 1 19 95 51 1 1 13 34 4,4 45 5 3 read more..

  • Page - 884

    Section D.1.1 Programming Cultural Differences 873 code’’ and the use of l lo oc ca al le es. The former (traditional) approach is feasible where we can ensure that every input operation can be easily converted from one convention to another. However, if the appearance of built-in types needs to vary, if different character sets are needed, or if we need to choose among read more..

  • Page - 885

    874 Locales Appendix D s st ta at ti ic c l lo oc ca al le e g gl lo ob ba al l(c co on ns st t l lo oc ca al le e&) ; / / set global locale and return old global locale s st ta at ti ic c c co on ns st t l lo oc ca al le e& c cl la as ss si ic c() ; / / get ‘‘classic’’ C-style locale p pr ri iv va at te e: read more..

  • Page - 886

    Section D.2.1 Named Locales 875 l lo oc ca al le e l lo oc c0 0; / / copy of the current global locale (§D.2.3) l lo oc ca al le e l lo oc c1 1 = l lo oc ca al le e() ; / / copy of the current global locale (§D.2.3) l lo oc ca al le e l lo oc c2 2("") ; / / copy of ‘‘the user’s preferred locale’’ l lo oc ca al le e l lo read more..

  • Page - 887

    876 Locales Appendix D v vo oi id d s se et t _ _l lo oc c(l lo oc ca al le e& l lo oc c, c co on ns st t c ch ha ar r* n na am me e) t tr ry y { l lo oc c = l lo oc ca al le e(n na am me e) ; } c ca at tc ch h ( r ru un nt ti im me e _ _e er rr ro or r) { c ce er rr r << " l lo oc ca al le read more..

  • Page - 888

    Section D.2.1.1 Constructing New Locales 877 D.2.1.1 Constructing New Locales A new locale is made by taking an existing l lo oc ca al le e and adding or replacing f fa ac ce et ts. Typically, a new l lo oc ca al le e is a minor variation on an existing one. For example: v vo oi id d f f(c co on ns st t l lo oc ca al le e& l lo oc c, c read more..

  • Page - 889

    878 Locales Appendix D v vo oi id d f f(c co on ns st t l lo oc ca al le e& l lo oc c, c co on ns st t l lo oc ca al le e& l lo oc c2 2) { l lo oc ca al le e l lo oc c3 3 = l lo oc c.c co om mb bi in ne e< M My y _ _m mo on ne ey y _ _i io o >( l lo oc c2 2) ; / / ... } The resulting l lo oc c3 read more..

  • Page - 890

    Section D.2.2 Copying and Comparing Locales 879 l lo oc c: : . . c co om mp pa ar re e() h ha as sh h() ... c co ol ll la at te e < <c ch ha ar r > >: : . . d de ec ci im ma al l _ _p po oi in nt t() c cu ur rr r _ _s sy ym mb bo ol l() ... n nu um mp pu un nc ct t < <c ch ha ar r > >: : . . d de ec ci read more..

  • Page - 891

    880 Locales Appendix D If a locale x x has a name string, l lo oc ca al le e: : g gl lo ob ba al l(x x) also sets the C global locale. This implies that if a C++ program calls a locale-sensitive function from the C standard library, the treatment of locale will be consistent throughout a mixed C and C++ program. If a locale x x does not have a name read more..

  • Page - 892

    Section D.3 Facets 881 p pr ri iv va at te e: f fa ac ce et t(c co on ns st t f fa ac ce et t&) ; / / not defined v vo oi id d o op pe er ra at to or r=(c co on ns st t f fa ac ce et t&) ; / / not defined / / representation }; The copy operations are p pr ri iv va at te e and are left undefined to prevent copying (§11.2.2). read more..

  • Page - 893

    882 Locales Appendix D The copy operations are declared private and are left undefined to prevent copying (§11.2.2). The intended use of i id d is for the user to define a s st ta at ti ic c member of type i id d of each class supply- ing a new f fa ac ce et t interface (for example, see §D.4.1). The l lo oc ca al le e mechanisms use i id ds to read more..

  • Page - 894

    Section D.3.1 Accessing Facets in a Locale 883 / / pseudoimplementation: imagine that a locale has a map <id,facet*> called facet _map t te em mp pl la at te e < c cl la as ss s F Fa ac ce et t> b bo oo ol l h ha as s _ _f fa ac ce et t(c co on ns st t l lo oc ca al le e& l lo oc c) t th hr ro ow w() { c co on ns st read more..

  • Page - 895

    884 Locales Appendix D s st ta at ti ic c l lo oc ca al le e: : i id d i id d; / / facet identifier object (§D.2, §D.3, §D.3.1) }; l lo oc ca al le e: : i id d S Se ea as so on n _ _i io o: : i id d; / / define the identifier object For simplicity, this f fa ac ce et t is limited to representations using c ch ha ar r. The S Se ea read more..

  • Page - 896

    Section D.3.2 A Simple User-Defined Facet 885 i in nt t m ma ai in n() / / trivial test { S Se ea as so on n x x; / / Use default locale (no Season _io facet) implies integer I/O: c ci in n >> x x; c co ou ut t << x x << e en nd dl l; l lo oc ca al le e l lo oc c(l lo oc ca al le e() , n ne ew w U US S _ _s se ea read more..

  • Page - 897

    886 Locales Appendix D b bo oo ol l U US S _ _s se ea as so on n _ _i io o: : f fr ro om m _ _s st tr r(c co on ns st t s st tr ri in ng g& s s, S Se ea as so on n& x x) c co on ns st t { c co on ns st t s st tr ri in ng g* b be eg g = & s se ea as so on ns s[s sp pr ri in ng g] ; c co on ns read more..

  • Page - 898

    Section D.4 Standard Facets 887 D.4 Standard Facets In < l lo oc ca al le e>, the standard library provides these f fa ac ce et ts for the c cl la as ss si ic c() locale: _ ___________________________________________________________________ Standard Facets (in the c cl la as ss si ic c( () ) locale) _ ___________________________________________________________________ _ read more..

  • Page - 899

    888 Locales Appendix D representation of a currency symbol is used (§D.4.3.1). The m mb bs st ta at te e _ _t t type is used to represent the shift states of a multibyte character representation (§D.4.6); m mb bs st ta at te e _ _t t is defined in < c cw wc ch ha ar r> and < w wc ch ha ar r.h h>. I In n and O Ou ut t are input read more..

  • Page - 900

    Section D.4 Standard Facets 889 rules of Danish (that give three extra vowels compared to English) but that retains the syntax of numbers used in C++: l lo oc ca al le e d dk k _ _u us s(l lo oc ca al le e: : c cl la as ss si ic c() , d dk k,c co ol ll la at te e|c ct ty yp pe e) ; / / Danish letters, American numbers The presentations of read more..

  • Page - 901

    890 Locales Appendix D Note that the destructor is protected. The c co ol ll la at te e facet isn’t meant to be used directly. Rather, it is intended as a base class for all (derived) collation classes and for l lo oc ca al le e to manage (§D.3). Application programmers, implementation providers, and library vendors will write the string com- parison facets to be read more..

  • Page - 902

    Section D.4.1 String Comparison 891 c co on ns st t C Co ol l& c co ol ll l = u us se e _ _f fa ac ce et t<C Co ol l>(l lo oc ca al le e(n n)) ; / / from locale named n i in nt t i i2 2 = c co ol ll l.c co om mp pa ar re e(c cs s1 1,c cs s1 1+s s1 1.s si iz ze e() , c cs s2 2,c cs s2 2+s s2 2.s si iz ze read more..

  • Page - 903

    892 Locales Appendix D D.4.1.1 Named Collate A c co ol ll la at te e _ _b by yn na am me e is a facet that provides a version of c co ol ll la at te e for a particular locale named by a constructor string argument: t te em mp pl la at te e < c cl la as ss s C Ch h> c cl la as ss s s st td d: : c co ol ll la at te e _ _b read more..

  • Page - 904

    Section D.4.2.1 Numeric Punctuation 893 D.4.2.1 Numeric Punctuation The n nu um mp pu un nc ct t facet defines the I/O format of built-in types, such as b bo oo ol l, i in nt t, and d do ou ub bl le e: t te em mp pl la at te e < c cl la as ss s C Ch h> c cl la as ss s s st td d: : n nu um mp pu un nc ct t : p pu ub bl li read more..

  • Page - 905

    894 Locales Appendix D v vo oi id d f f() { c co ou ut t << " s st ty yl le e A A: " << 1 12 23 34 45 56 67 78 8 << " *** "<< 1 12 23 34 45 56 67 7.8 8 << ´ \ \n n´; l lo oc ca al le e l lo oc c(l lo oc ca al le e() , n ne ew w M My y _ _p pu un nc ct t) ; c co ou ut t.i im mb read more..

  • Page - 906

    Section D.4.2.2 Numeric Output 895 that iterator positioned one past the last character position written. Note that the default specialization of n nu um m _ _p pu ut t (the one where the iterator used to access char- acters is of type o os st tr re ea am mb bu uf f _ _i it te er ra at to or r<C Ch h>) is part of the standard locales (§D.4). If you read more..

  • Page - 907

    896 Locales Appendix D t tr ry y { i if f ( u us se e _ _f fa ac ce et t< n nu um m _ _p pu ut t<C Ch h> >(g ge et tl lo oc c()).p pu ut t(*t th hi is s,*t th hi is s,t th hi is s->f fi il ll l() , d d).f fa ai il le ed d()) s se et ts st ta at te e(b ba ad db bi it t) ; } c ca at tc ch h (...) { h ha read more..

  • Page - 908

    Section D.4.2.3 Numeric Input 897 D.4.2.3 Numeric Input When reading from a stream buffer (§21.6.4), an i is st tr re ea am m relies on the n nu um m _ _g ge et t facet: t te em mp pl la at te e < c cl la as ss s C Ch h, c cl la as ss s I In n = i is st tr re ea am mb bu uf f _ _i it te er ra at to or r<C Ch h> > c read more..

  • Page - 909

    898 Locales Appendix D t tr ry y { u us se e _ _f fa ac ce et t< n nu um m _ _g ge et t<C Ch h> >(g ge et tl lo oc c()).g ge et t(*t th hi is s,e eo os s,*t th hi is s,s st ta at te e,d dd d) ; i if f ( s st ta at te e==0 0 || s st ta at te e==e eo of fb bi it t) d d = d dd d; / / set value only if get() read more..

  • Page - 910

    Section D.4.3 Input and Output of Monetary Values 899 / / ... v vo oi id d f f(l lo on ng g i in nt t i i) { c co ou ut t << " v va al lu ue e= " << i i << " a am mo ou un nt t= " << M Mo on ne ey y(i i) << e en nd dl l; } The task of the monetary facets is to make it reasonably easy to write an read more..

  • Page - 911

    900 Locales Appendix D t te em mp pl la at te e < c cl la as ss s C Ch h, b bo oo ol l I In nt te er rn na at ti io on na al l = f fa al ls se e> c cl la as ss s s st td d: : m mo on ne ey yp pu un nc ct t : p pu ub bl li ic c l lo oc ca al le e: : f fa ac ce et t, p pu ub bl li ic c m mo on read more..

  • Page - 912

    Section D.4.3.1 Money Punctuation 901 +$ 1 12 23 3.4 45 5 / / { sign, symbol, space, value } where positive _sign() returns "+" $+ 1 12 23 3.4 45 5 / / { symbol, sign, value, none } where positive _sign() returns "+" $ 1 12 23 3.4 45 5 / / { symbol, sign, value, none } where positive _sign() returns "" $ 1 12 23 3.4 45 5- / / { symbol, read more..

  • Page - 913

    902 Locales Appendix D p pa at tt te er rn n d do o _ _n ne eg g _ _f fo or rm ma at t() c co on ns st t { s st ta at ti ic c p pa at tt te er rn n p pa at t = { s si ig gn n, s sy ym mb bo ol l, v va al lu ue e, n no on ne e }; r re et tu ur rn n p pa at t; } }; This facet is used in the M Mo on ne ey read more..

  • Page - 914

    Section D.4.3.2 Money Output 903 t tr ry y { c co on ns st t m mo on ne ey y _ _p pu ut t<c ch ha ar r>& f f = u us se e _ _f fa ac ce et t< m mo on ne ey y _ _p pu ut t<c ch ha ar r> >(s s.g ge et tl lo oc c()) ; i if f ( m m==s st ta at ti ic c _ _c ca as st t<l lo on ng g d do ou ub bl le read more..

  • Page - 915

    904 Locales Appendix D A well-defined pair of m mo on ne ey y _ _g ge et t and m mo on ne ey y _ _p pu ut t facets will provide output in a form that can be read back in without errors or loss of information. For example: i in nt t m ma ai in n() { M Mo on ne ey y m m; w wh hi il le e ( c ci in n>>m m) c co ou ut t << m read more..

  • Page - 916

    Section D.4.4.1 Clocks and Timers 905 D.4.4.1 Clocks and Timers At the lowest level, most systems have a fine-grained timer. The standard library provides a func- tion c cl lo oc ck k() that returns an implementation-defined arithmetic type c cl lo oc ck k _ _t t. The result of c cl lo oc ck k() can be calibrated by using the C CL LO OC CK KS S _ _P PE ER read more..

  • Page - 917

    906 Locales Appendix D t ty yp pe ed de ef f i im mp pl le em me en nt ta at ti io on n _ _d de ef fi in ne ed d t ti im me e _ _t t; / / implementation-defined arithmetic type (§4.1.1) / / capable of representing a period of time, / / often, a 32-bit integer s st tr ru uc ct t t tm m { i in nt t t tm m _ _s se ec c; / / second read more..

  • Page - 918

    Section D.4.4.1 Clocks and Timers 907 [1970,2038] range. People who want to represent dates outside the 1970 to 2038 time frame must devise some additional mechanism to do so. One consequence of this is that m mk kt ti im me e() can fail. If the argument for m mk kt ti im me e() cannot be represented as a t ti im me e _ _t t, the error indicator t ti im read more..

  • Page - 919

    908 Locales Appendix D / / ... p pr ri iv va at te e: t ti im me e _ _t t d d; / / standard date and time representation }; D Da at te e: : D Da at te e(i in nt t d dd d, M Mo on nt th h m mm m, i in nt t y yy y) { t tm m x x = { 0 0 }; i if f ( d dd d<0 0 || 3 31 1<d dd d) t th hr ro ow w B Ba ad d _ _d read more..

  • Page - 920

    Section D.4.4.3 Date and Time Output 909 actual output and may contain the following special-purpose format specifiers: % %a a abbreviated weekday name (e.g., Sat) % %A A full weekday name (e.g., Saturday) % %b b abbreviated month name (e.g., Feb) % %B B full month name (e.g., February) % %c c date and time (e.g., Sat Feb 06 21:46:05 1999) % %d d day of month [01,31] (e.g., read more..

  • Page - 921

    910 Locales Appendix D On a Wednesday, this will print W We ed dn ne es sd da ay y in the default c cl la as ss si ic c() locale (§D.2.3) and o on ns sd da ag g in a Danish locale. Characters that are not part of a format specified, such as the newline in the example, are simply copied into the first argument (s s). When p pu ut t() identifies a read more..

  • Page - 922

    Section D.4.4.4 Date and Time Input 911 read the times and dates produced by the l lo oc ca al le e’s t ti im me e _ _p pu ut t. However, there are no standard d da at te e and t ti im me e classes, so a programmer can use a locale to produce output according to a variety of for- mats. For example, the following representations could all be produced read more..

  • Page - 923

    912 Locales Appendix D The g ge et t _ _t ti im me e() function calls d do o _ _g ge et t _ _t ti im me e(). The default g ge et t _ _t ti im me e() reads time as produced by the l lo oc ca al le e’s t ti im me e _ _p pu ut t: : p pu ut t(), using the % X X format (§D.4.4). Similarly, the g ge et t _ _d da at te e() read more..

  • Page - 924

    Section D.4.4.4 Date and Time Input 913 D.4.4.5 A More Flexible Date Class If you tried to use the D Da at te e class from §D.4.4.2 with the I/O from §D.4.4.3 and §D.4.4.4, you’d soon find it restrictive: [1] It can handle only dates that can be represented by a t ti im me e _ _t t; that typically means in the [1970,2038] range. [2] It accepts dates only in the read more..

  • Page - 925

    914 Locales Appendix D i if f ( d dd d<1 1 || 3 31 1<d dd d) / / oversimplified; see §10.3.1 t th hr ro ow w B Ba ad d _ _d da at te e("b ba ad d d da ay y o of f m mo on nt th h") ; i if f ( d da ay y _ _o of f _ _w we ee ek k && d da ay y _ _i in n _ _w we ee ek k(y yy y,m mm m,d dd d)!=d da read more..

  • Page - 926

    Section D.4.4.6 Specifying a D Da at te e Format 915 c cl la as ss s D Da at te e _ _f fo or rm ma at t { s st ta at ti ic c c ch ha ar r f fm mt t[] ; / / default format c co on ns st t c ch ha ar r* c cu ur rr r; / / current format c co on ns st t c ch ha ar r* c cu ur rr r _ _e en nd d; p pu ub bl li ic c: read more..

  • Page - 927

    916 Locales Appendix D Here is a simple test program that controls the output format through d da at te e _ _f fm mt t: i in nt t m ma ai in n() t tr ry y { w wh hi il le e ( c ci in n >> d dd d && d dd d != D Da at te e()) c co ou ut t << d dd d << e en nd dl l; / / write using default date _fmt d da at read more..

  • Page - 928

    Section D.4.4.7 A D Da at te e Input Facet 917 p pr ro ot te ec ct te ed d: I In n d do o _ _g ge et t _ _d da at te e(I In n b b, I In n e e, i io os s _ _b ba as se e& s s, i io os s _ _b ba as se e: : i io os st ta at te e& r r, t tm m* t tm mp p) c co on ns st t; p pr ri iv va at te e: e en read more..

  • Page - 929

    918 Locales Appendix D * v v = i i; * r re es s = u un nk kn no ow wn n; / / an integer, but we don’t know what it represents r re et tu ur rn n b b; } i if f ( c ct t.i is s(c ct ty yp pe e _ _b ba as se e: : a al lp ph ha a,c c)) { / / look for name of month or day of week b ba as si ic c _ _s st tr ri in ng read more..

  • Page - 930

    Section D.4.4.7 A D Da at te e Input Facet 919 t te em mp pl la at te e<c cl la as ss s C Ch h, c cl la as ss s I In n> I In n D Da at te e _ _i in n<C Ch h,I In n>: : d do o _ _g ge et t _ _d da at te e(I In n b b, I In n e e, i io os s _ _b ba as se e& s s, i io os s _ _b ba as se e: : i read more..

  • Page - 931

    920 Locales Appendix D I have omitted bits of code that do not add to the understanding of locales, dates, or the handling of input. Writing better and more general date input functions are left as exercises (§D.6[9-10]). Here is a simple test program: i in nt t m ma ai in n() t tr ry y { c ci in n.i im mb bu ue e(l lo oc c(l lo oc ca al le e() , n read more..

  • Page - 932

    Section D.4.5 Character Classification 921 c cl la as ss s s st td d: : c ct ty yp pe e _ _b ba as se e { p pu ub bl li ic c: e en nu um m m ma as sk k { / / the actual values are implementation defined s sp pa ac ce e = 1 1, / / whitespace (in "C" locale: ’ ’, ’\n’, ’\t’, ...) p pr ri in nt t = 1 1<<1 1, / / read more..

  • Page - 933

    922 Locales Appendix D C Ch h t to ou up pp pe er r(C Ch h c c) c co on ns st t; c co on ns st t C Ch h* t to ou up pp pe er r(C Ch h* b b, c co on ns st t C Ch h* e e) c co on ns st t; / / convert [b:e) C Ch h t to ol lo ow we er r(C Ch h c c) c co on ns st t; c co on ns st t C Ch h* t to ol lo ow read more..

  • Page - 934

    Section D.4.5 Character Classification 923 t te em mp pl la at te e < c cl la as ss s C Ch h> c co on ns st t C Ch h* s st td d: : c ct ty yp pe e<C Ch h>: : t to o _ _u up pp pe er r(C Ch h* b b, c co on ns st t C Ch h* e e) { f fo or r (; b b!=e e; ++ b b) * b b = t to ou up pp pe er r(*b b) ; r re read more..

  • Page - 935

    924 Locales Appendix D For example: w wi id de en n(n na ar rr ro ow w(´x x´) , 0 0) == ´ x x´ The n na ar rr ro ow w() and w wi id de en n() functions respect character classifications wherever possible. For example, if i is s(a al lp ph ha a,c c), then i is s(a al lp ph ha a,n na ar rr ro ow w(c c,´a a´)) and i is s(a al lp ph ha read more..

  • Page - 936

    Section D.4.5.1 Convenience Interfaces 925 D.4.6 Character Code Conversion Sometimes, the representation of characters stored in a file differs from the desired representation of those same characters in main memory. For example, Japanese characters are often stored in files in which indicators (‘‘shifts’’) tell to which of the four common character sets (kanji, kata- kana, hiragana, read more..

  • Page - 937

    926 Locales Appendix D r re es su ul lt t o ou ut t(S St ta at te e&, c co on ns st t I I* f fr ro om m, c co on ns st t I I* f fr ro om m _ _e en nd d, c co on ns st t I I*& f fr ro om m _ _n ne ex xt t,/ / write E E* t to o, E E* t to o _ _e en nd d, E E*& t to o _ _n ne ex xt t) c co on read more..

  • Page - 938

    Section D.4.6 Character Code Conversion 927 The s s argument of type S St ta at te e indicates the state of the input character sequence at the start of the call of i in n(). This is significant when the external character representation uses shift states. Note that s s is a (non-c co on ns st t) reference argument: At the end of the call, s s holds the read more..

  • Page - 939

    928 Locales Appendix D r re es su ul lt t d do o _ _u un ns sh hi if ft t(S St ta at te e&, E E* t to o, E E* t to o _ _e en nd d, E E*& t to o _ _n ne ex xt t) c co on ns st t { r re et tu ur rn n o ok k; } i in nt t d do o _ _e en nc co od di in ng g() c co on ns st t t th hr ro ow w() { r read more..

  • Page - 940

    Section D.4.7 Messages 929 c ca at ta al lo og g o op pe en n(c co on ns st t b ba as si ic c _ _s st tr ri in ng g<c ch ha ar r>& f fn n, c co on ns st t l lo oc ca al le e&) c co on ns st t; s st tr ri in ng g _ _t ty yp pe e g ge et t(c ca at ta al lo og g c c, i in nt t s se et t, i in nt read more..

  • Page - 941

    930 Locales Appendix D s st tr ri in ng g M My y _ _m me es ss sa ag ge es s: : d do o _ _g ge et t(c ca at ta al lo og g c ca at t, i in nt t s se et t, i in nt t m ms sg g, c co on ns st t s st tr ri in ng g& d de ef f) c co on ns st t { i if f ( c ca at ta al lo og gs s.s si iz ze e()<=c ca read more..

  • Page - 942

    Section D.4.7 Messages 931 c co ou ut t << m m.g ge et t(c ca at t,1 1,3 3,"M Mi is ss se ed d a ag ga ai in n!") << e en nd dl l; c co ou ut t << m m.g ge et t(c ca at t,3 3,0 0,"M Mi is ss se ed d a ag ga ai in n!") << e en nd dl l; } If the catalog is <<< h he el ll lo o g go oo od read more..

  • Page - 943

    932 Locales Appendix D c co on ns st t s st tr ri in ng g& S Se ea as so on n _ _i io o: : t to o _ _s st tr r(S Se ea as so on n x x) c co on ns st t { r re et tu ur rn n m m->g ge et t(c ca at t,x x,"n no o-s su uc ch h-s se ea as so on n") ; } b bo oo ol l S Se ea as so on n _ _i io o: : f read more..

  • Page - 944

    Section D.6 Exercises 933 D.6 Exercises 1. ( ∗2.5) Define a S Se ea as so on n _ _i io o (§D.3.2) for a language other than American English. 2. ( ∗2) Define a S Se ea as so on n _ _i io o (§D.3.2) class that takes a set of name strings as a constructor argu- ment so that S Se ea as so on n names for different locales can be represented as objects of this class. 3. ( ∗3) read more..

  • Page - 945

    _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Appendix E _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Standard-Library Exception Safety Everything will work read more..

  • Page - 946

    936 Standard-Library Exception Safety Appendix E What happens if the assignment throws an exception while trying to copy g g? Will v v be left with an invalid element? What happens if the constructor that v v.p pu us sh h _ _b ba ac ck k() uses to copy g g throws s st td d: : b ba ad d _ _a al ll lo oc c? Has the number of elements changed? Has an read more..

  • Page - 947

    Section E.2 Exception Safety 937 that valid state to be one that doesn’t suit the application. For example, a string may have been left as the empty string or a container may have been left unsorted. Thus, ‘‘repair’’ means giving an object a value that is more appropriate/desirable for the application than the one it was left with after an operation failed. In the read more..

  • Page - 948

    938 Standard-Library Exception Safety Appendix E U Un ns sa af fe e& o op pe er ra at to or r=(c co on ns st t U Un ns sa af fe e& a a) { p p->˜T T() ; / / destroy old value (§10.4.11) n ne ew w(p p) T T(a a.p p) ; / / construct copy of a.p in *p (§10.4.11) r re et tu ur rn n * t th hi is s; } / / ... }; v vo oi id d f read more..

  • Page - 949

    Section E.2 Exception Safety 939 example, if you throw an exception from a destructor for a v ve ec ct to or r element, you have no more rea- son to hope for a reasonable result than if you dereference a pointer initialized to a random number: c cl la as ss s B Bo om mb b { p pu ub bl li ic c: / / ... ˜ B Bo om mb b() { t th hr ro ow w T read more..

  • Page - 950

    940 Standard-Library Exception Safety Appendix E E.3 Exception-Safe Implementation Techniques As usual, the standard library provides examples of problems that occur in many other contexts and of solutions that apply widely. The basic tools available for writing exception-safe code are [1] the try-block (§8.3.1), and [2] the support for the ‘‘resource acquisition is initialization’’ technique read more..

  • Page - 951

    Section E.3.1 A Simple Vector 941 p pu ub bl li ic c: e ex xp pl li ic ci it t v ve ec ct to or r(s si iz ze e _ _t ty yp pe e n n, c co on ns st t T T& v va al l = T T() , c co on ns st t A A& = A A()) ; v ve ec ct to or r(c co on ns st t v ve ec ct to or r& a a) ; / / copy constructor v ve ec ct read more..

  • Page - 952

    942 Standard-Library Exception Safety Appendix E c ca at tc ch h (...) { f fo or r ( i it te er ra at to or r q q = v v; q q!=p p; ++ q q) a al ll lo oc c.d de es st tr ro oy y(q q) ; / / destroy constructed elements a al ll lo oc c.d de ea al ll lo oc ca at te e(v v,n n) ; / / free memory t th hr ro ow w; / / re-throw } } read more..

  • Page - 953

    Section E.3.1 A Simple Vector 943 t te em mp pl la at te e<c cl la as ss s T T, c cl la as ss s A A> v ve ec ct to or r<T T,A A>: : v ve ec ct to or r(s si iz ze e _ _t ty yp pe e n n, c co on ns st t T T& v va al l, c co on ns st t A A& a a) / / messy implementation : a al ll lo oc c(a a) / / read more..

  • Page - 954

    944 Standard-Library Exception Safety Appendix E memory for a type T T, not objects of type T T. Consequently, a user of v ve ec ct to or r _ _b ba as se e must destroy all constructed objects in a v ve ec ct to or r _ _b ba as se e before the v ve ec ct to or r _ _b ba as se e itself is destroyed. Naturally, v ve ec ct to or r _ _b ba read more..

  • Page - 955

    Section E.3.2 Representing Memory Explicitly 945 t te em mp pl la at te e<c cl la as ss s T T, c cl la as ss s A A> v ve ec ct to or r<T T,A A>: : v ve ec ct to or r(c co on ns st t v ve ec ct to or r<T T,A A>& a a) : v ve ec ct to or r _ _b ba as se e<T T,A A>(a a.a al ll lo oc c,a a.s si iz ze read more..

  • Page - 956

    946 Standard-Library Exception Safety Appendix E of self-assignment was more than offset by its cost in the common case where a different v ve ec ct to or r is assigned. In either case, two potentially significant optimizations are missing: [1] If the capacity of the vector assigned to is large enough to hold the assigned vector, we don’t need to allocate new memory. [2] read more..

  • Page - 957

    Section E.3.3 Assignment 947 The standard-library v ve ec ct to or r assignment offers the weaker exception-safety property of this last implementation – and its potential performance advantages. That is, v ve ec ct to or r assignment provides the basic guarantee, so it meets most people’s idea of exception safety. However, it does not pro- vide the strong guarantee (§E.2). read more..

  • Page - 958

    948 Standard-Library Exception Safety Appendix E t te em mp pl la at te e< c cl la as ss s T T, c cl la as ss s A A> v vo oi id d v ve ec ct to or r<T T,A A>: : p pu us sh h _ _b ba ac ck k(c co on ns st t T T& x x) { i if f ( s sp pa ac ce e == l la as st t) { / / no more free space; relocate: v ve ec read more..

  • Page - 959

    Section E.3.5 Constructors and Invariants 949 E.3.5 Constructors and Invariants From the point of view of exception safety, other v ve ec ct to or r operations are either equivalent to the ones already examined (because they acquire and release resources in similar ways) or trivial (because they don’t perform operations that require cleverness to maintain valid states). However, read more..

  • Page - 960

    950 Standard-Library Exception Safety Appendix E Note that this attempt to write safer code complicates the invariant for the class: It is no longer guaranteed that v v points to allocated memory. Now v v might be 0 0. This has one immediate cost. The standard-library requirements for allocators do not guarantee that we can safely deallocate a pointer with the value 0 0 read more..

  • Page - 961

    Section E.3.5.1 Using i in ni it t( () ) Functions 951 i in nt t f f1 1(i in nt t n n) { v ve ec ct to or r<X X> v v; / / ... i if f ( v v.i in ni it t(n n)) { / / use v as vector of n elements } e el ls se e { / / handle _problem } } and i in nt t f f2 2(i in nt t n n) t tr ry y { v ve ec ct to or r v v<X read more..

  • Page - 962

    952 Standard-Library Exception Safety Appendix E t te em mp pl la at te e< c cl la as ss s T T> T T& v ve ec ct to or r<T T>: : a at t(s si iz ze e _ _t t i i) { i if f ( i i<v v.s si iz ze e()) r re et tu ur rn n v v[i i] ; t th hr ro ow w o ou ut t _ _o of f _ _r ra an ng ge e("v ve ec ct to or read more..

  • Page - 963

    Section E.3.5.2 Relying on a Default Valid State 953 have a problem. However, this ‘‘safe state’’ should be one that is a natural part of the semantics of the class rather than an implementation artifact that complicates the class invariant. E.3.5.3 Delaying resource acquisition Like the second point (§E.3.5.2), the third (to delay acquisition until a resource is needed) misap- plies a good idea in read more..

  • Page - 964

    954 Standard-Library Exception Safety Appendix E library implementers, for library users, and for people trying to understand code – come when a user-supplied function throws an exception. The standard-library containers offer the basic guarantee (§E.2): The basic invariants of the library are maintained, and no resources are leaked as long as user code behaves as required. That is, read more..

  • Page - 965

    Section E.4.1 Insertion and Removal of Elements 955 E.4.1 Insertion and Removal of Elements Inserting an element into a container and removing one are obvious examples of operations that might leave a container in an unpredictable state if an exception is thrown. The reason is that inser- tions and deletions invoke many operations that may throw exceptions: [1] A new value is read more..

  • Page - 966

    956 Standard-Library Exception Safety Appendix E These rules can be summarized in a table: _ ______________________________________________________________________ Container-Operation Guarantees _ ______________________________________________________________________ _ ______________________________________________________________________ vector deque list map _ ______________________________________________________________________ c cl le read more..

  • Page - 967

    Section E.4.1 Insertion and Removal of Elements 957 The s sw wa ap p() functions differ from the other functions mentioned by not being members. The guarantee for c cl le ea ar r() is derived from that offered by e er ra as se e() (§16.3.6). This table lists guarantees offered in addition to the basic guarantee. Consequently this table does not list oper- ations, read more..

  • Page - 968

    958 Standard-Library Exception Safety Appendix E t tr ry y { v ve ec c.p pu us sh h _ _b ba ac ck k(x x) ; / / add to vector } c ca at tc ch h (...) { / / vec is unchanged r re et tu ur rn n; } / / lst and vec each have a new element with the value x } Providing the strong guarantee in these cases is simple and cheap. It is also very useful read more..

  • Page - 969

    Section E.4.2 Guarantees and Tradeoffs 959 t tr ry y { m m.i in ns se er rt t(m ma ak ke e _ _p pa ai ir r(s s,x x)) ; / / add to map } c ca at tc ch h (...) { / / m is unchanged r re et tu ur rn n; } / / lst and vec each have a new element with the value x / / m has an element with the value (s,x) } If X X: : c ca an nn no ot read more..

  • Page - 970

    960 Standard-Library Exception Safety Appendix E E.4.3 Swap Like copy constructors and assignments, s sw wa ap p() operations are essential to many standard algorithms and are often supplied by users. For example, s so or rt t() and s st ta ab bl le e _ _s so or rt t() typically reorder elements, using s sw wa ap p(). Thus, if a s sw wa ap p() function throws read more..

  • Page - 971

    Section E.4.4 Initialization and Iterators 961 Iterators are examples of objects that are copied freely by standard algorithms and opera- tions on standard containers. Thus, copy constructors and copy assignments of iterators should not throw exceptions. In particular, the standard guarantees that no copy constructor or assign- ment operator of an iterator returned from a standard read more..

  • Page - 972

    962 Standard-Library Exception Safety Appendix E might leave the free store corrupted in a way that causes difficult-to-track problems much later on in an apparently unrelated part of a program. This possibility of corruption should not stop people from manipulating container elements through references and iterators; it is often the simplest and most efficient way of doing things. read more..

  • Page - 973

    Section E.5.1 Strings 963 E.5.1 Strings The operations on s st tr ri in ng gs can throw a variety of exceptions. However, b ba as si ic c _ _s st tr ri in ng g manipu- lates its characters through the functions provided by c ch ha ar r _ _t tr ra ai it ts s (§20.2), and these functions are not allowed to throw exceptions. That is, the c ch ha ar r _ _t read more..

  • Page - 974

    964 Standard-Library Exception Safety Appendix E must originate from a user-supplied operation. That is, the exception must come from an opera- tion on an element – such as a predicate (§18.4), an assignment, or a s sw wa ap p() – or from an allo- cator (§19.4). If such an operation throws an exception, the algorithm terminates immediately, and it is up to the functions that read more..

  • Page - 975

    Section E.6 Implications for Library Users 965 E.6 Implications for Library Users One way to look at exception safety in the context of the standard library is that we have no problems unless we create them for ourselves: The library will function correctly as long as user-supplied operations meet the standard library’s basic requirements (§E.2). In particular, no exception read more..

  • Page - 976

    966 Standard-Library Exception Safety Appendix E pessimistic approach to error handling and recovery. For example, a v ve ec ct to or r<T T*> is trivially exception safe if operations on T T don’t throw exceptions. However, unless the objects pointed to are deleted somewhere, an exception from the v ve ec ct to or r will lead to a resource leak. Thus, introducing a read more..

  • Page - 977

    Section E.7 Advice 967 E.7 Advice [1] Be clear about what degree of exception safety you want; §E.2. [2] Exception safety should be part of an overall strategy for fault tolerance; §E.2. [3] Provide the basic guarantee for all classes. That is, maintain an invariant, and don’t leak resources; §E.2, §E.3.2, §E.4. [4] Where possible and affordable, provide the strong guarantee read more..

  • Page - 978

    968 Standard-Library Exception Safety Appendix E s sa af fe e _ _a as ss si ig gn n() (§E.3.3). 9. ( ∗1.5) Copy an allocator without using an assignment operator (as needed to improve o op pe er ra at to or r=() in §E.3.3). 10. ( ∗2) Add single-element and multiple-element e er ra as se e() and i in ns se er rt t() that provide the basic guarantee to v read more..

  • Page - 979

    _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ I _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Index Is there another word for synonym? – anon ## 162 ** read more..

  • Page - 980

    870 Index iterator 551 plus 517 string 593 user-defined 265 user-defined operator 281 valarray 667 ++ increment operator 125 iterator 551 user-defined operator 264, 291 += advance() and 551 complex 679 iterator 551 operator 109 string 592 user-defined operator 264, 268, 281 valarray 664 - complex 680 distance() and 551, 554 iterator 551 minus 517 negate 517 valarray 664, 667 -- decrement operator 125 read more..

  • Page - 981

    Index 871 equal_to 516 equality without 468 iterator 551 string 591 user-defined 534 valarray 667 vector 457 > and >> 812 generated 468 greater 516 iterator 551 string 591 valarray 667 >= generated 468 greater_equal 516 iterator 551 string 591 valarray 667 >> > and 812 bitset 494 bitset 495 char 615 complex 680 extractor 608 get from 607 input cin 50, 112 istream 614 of complex 621 of read more..

  • Page - 982

    872 Index – A – to base 850 to member 849 to member class 851 unchecked 445 accumulate() 682 acos() , valarray 667 acquisition, resource 364 action 776 Ada 10, 725 adapter member function 520 pointer to function 521 adapters, container 469 add element to sequence 529 adding to container 555 to sequence 555 to standard library 434 address of element 454 addressing, united of 88 read more..

  • Page - 983

    – A – Index 873 array 147 command line 117 deducing template 335, 855 default 153 depend on template 861 explicit template 335 function template 335 passing 283 passing, function 145 reference 98 template 331 type check, function 145 type conversion, function 145 type, difference from C 817 types, virtual function 310 undeclared 154 value, example of default 227 argv argc , main() 117 read more..

  • Page - 984

    874 Index – B – B \b , backspace 830 back() 445 of queue 476 back_inserter() 57, 555 back_insert_iterator 555 backslash \ 830 backspace \b 830 bad() 616 bad_alloc 129 and new 384 exception 576 missing 823 badbit 617 bad_cast 410 and dynamic_cast 384 bad_exception 378, 384 bad_typeid and typeid() 384 balance 695 base access to 850 and derived class 39, 737 class 303 class, access control and 405 read more..

  • Page - 985

    – B – Index 875 bits in char 658 in float 658 in int 658 <bitset> 431 bitset 492 494 != 494 & 495 &= of 494 << 495 << 494 <<= of 494 == 494 >> 495 >> 494 >>= of 494 [] 494 ^ 495 ^= of 494 and bit field 492 and enum 492 and set 492 and vector<bool> 492 constructor 493 flip() 494 input 495 operation 494 output 495 reset() 494 set() 494 | 495 read more..

  • Page - 986

    876 Index – C – by reference 98, 146 by value 146 function 145 of destructor, explicit 256 callback 371 stream 650 call-by reference 282 callC() example 384 call_from_C() example 384 calloc() 577 capacity() 455 car factory analogy 698 Car example 772 card, CRC 703 c_array 496 carriage return \r 830 CASE 711, 725, 730 case and break 134 case-sensitive compare 591 <cassert> 432 cast C-style read more..

  • Page - 987

    – C – Index 877 compare() 581 copy() 581 eof() 581 eq() 581 eq_int_type() 581 find() 581 get_state() 581 int_type() 581 length() 581 lt() 581 move() 581 not_eof() 581 off_type 581 pos_type 581 state_type 581 to_char_type() 581 to_int_type() 581 char_traits<char> 580 char_traits<wchart> 581 char_type 608 char_traits 580 check, range 445, 561 checked access 445 iterator 561 pointer 291 Checked example 565 read more..

  • Page - 988

    878 Index – C – and concepts 732 and real-world 734 design and 732 find the 702 finding the 734 stream 637 use of 733 classic() locale 649 classification 703 cleanup, initialization and 364 clear goal 698 clear() , 487, 616 failure and 385 <climits> 433, 660 <clocale> 433, 650 Clock example 398 clog 609 cerr and 624 initialization 637 clone 424 clone() 426 close() 639 closing of read more..

  • Page - 989

    – C – Index 879 computation, numerical 64 concatenation, string 592– 593 concept 15 and class 301 class and 223 independent 327 concepts, classes and 732 concrete class 236, 241, 766 class, derive from 780 node class 774 type 33, 236, 766– 767 type, abstract and 771 type and derivation 768 type, problems with 37 type, reuse of 241 type, reuse of 768 condition 753 declaration in read more..

  • Page - 990

    880 Index – C – operation on 464 optimal 435 representation of 465 sequence and 512 standard library 56 standard-library 442 string as 491 summary 464 user-defined 497 valarray as 492 containers 431 containment 738 and inheritance 740 context of template definition 860 of template instantiation 860 continue 116 statement 116 contravariance 420 control, format 625 controlled statement 136 convenience read more..

  • Page - 991

    – C – Index 881 cast 131 cast, deprecated 819 error handling 661 function and algorithm 522 initialization, constructor and 270 string and const 90 string, string and 579 string, string and 589 <ctime> 431, 433 <ctype.h> 432, 601 cur , seekdir and curbing code bloat 342 Currying 520 <cwchar> 432 <cwtype> 432, 601 <cwtype.h> 601 cycle, development 698 D data abstraction read more..

  • Page - 992

    882 Index – D – without virtual 780 derived and friend 852 class 15, 303 class , base and 39, 737 class, constructor for 306 class, destructor for 306 class, member of 304 exceptions 359 design 696 I/O 605 abstract class and 318 aims 700 algorithm 510 alternative 710 and analysis 696 and classes 732 and language 724 and language, gap between 725 and programming 692 bibliography 719 read more..

  • Page - 993

    – D – Index 883 # , preprocessing 813 template instantiation 866 discrimination of exception 188 disguised pointer 844 dispatch, double 326 distance() and - 551, 554 distribution exponential 685 uniform 685 div() 661 divide and conquer, complexity 693 divides / 517 div_t 661 do statement 114, 137 documentation 714– 715 do_it() example 777 domain error 661 dominance 401 Donald Knuth 713 dot read more..

  • Page - 994

    884 Index – E – without == 468 equal_range() 540 in map 485 equal_to == 516 equivalence, type 104 Erand 685 ERANGE 601, 661 erase() from map 487 from vector 452 in string 595 errno 383, 601, 661 <errno.h> 432 error analysis 711 design 711 domain 661 exception and 622 handling 115, 186, 383, 566 handling, C-style 661 handling alternative 192, 355 handling, multilevel 383 linkage 199 loop read more..

  • Page - 995

    – E – Index 885 and function 375 and interface 375 and main() 54 and member initialization 373 and multiple inheritance 360 and new 367, 369 and recursive function 374 atexit() and 382 bad_alloc 576 catch every 54 container algorithm 566 copy of 362 cost of 381 discrimination of 188 handler 812 in constructor 367 in destructor 373 mapping 378 new and 576 qsort() and 382 standard 384 read more..

  • Page - 996

    886 Index – F – find the classes 702 find() 57, 525 char_traits 581 in map 485 in string 594 find_end() 528 find_first_not_of() in string 594 find_first_of() 525 in string 594 find_if() 62, 525 finding the classes 734 find_last() 444 find_last_of() in string 594 firewall 383 first C++ library 686 element 445 first-time switch 253, 640 fixed 626, 628 fixed() 634 flag manipulation 626 flags() 626 read more..

  • Page - 997

    – F – Index 887 and algorithm, C-style 522 argument passing 145 argument type check 145 argument type conversion 145 argument types, virtual 310 call 145 call and assignment 99 call, difference from C 816 class 776 const member 229 declaration 143 definition 144 definition, difference from C 817 definition of virtual 310 definition, old-style 817 example of virtual 646 exception and 375 read more..

  • Page - 998

    888 Index – G – namespace 847 object 244, 252 objects 640 scope 82, 847 variable 200, 228 variable, constructor for 252 variable, use of 111 global() locale 649 goal, clear 698 good() 616 goodbit 617 goto difference from C initialization and 818 nonlocal 357 statement 137 gptr() 645 gradual adoption of C++ 718 approach to learning C++ 7 grammar 793 graph, directed acyclic 308 greater > read more..

  • Page - 999

    – I – Index 889 ifstream 638 ignore() 618 imag() 679– 680 imbue() 645, 647, 650 imbue_event 651 imbue_event , imbue() 651 implementation alternative 320 and interface 317 dependency type of integer literal 832 inheritance 400, 743 interface and 224, 314, 399, 758, 771 iterator 59 of I/O 606 of RTTI 409 of container 465 of dynamic_cast 409 of virtual function 36 pre-standard 820 priority_queue read more..

  • Page - 1000

    890 Index – I – into container 451 into vector 451 iterator 550 manipulator 632 of bool 615 of built-in type 614 of char 615 of pointer 615 of user-defined type 621 sequence 513 string 598 unbuffered 642 unformatted 618 valarray 668 width() of 616 input_iterator_tag 553 insert() 55 [] and 488 into map 487 into vector 452 string 592 inserter, << 608 inserter() 555 insertion, overwriting vs read more..

  • Page - 1001

    – I – Index 891 iostate 617, 822 io_state 822 <iostream> 46, 432, 609, 614 <istream> and 613 <ostream> and 608 iostream 637 sentry 624 is-a 741 isalnum() 601 isalpha() 113, 601 is_bounded 659 iscntrl() 601 isdigit() 601 Iseq 513 iseq() example 513 is_exact 659 isgraph() 601 is_iec559 IEC-559 659 is_integer 658 islower() 601 is_modulo 659 ISO 646 829 C++ 11 isprint() 601 is_signed 658 isspace() read more..

  • Page - 1002

    892 Index – K – K keeping consistent declarations 201 Kernighan and Ritchie 654 key 55 and value 480 key, duplicate 480, 490 unique 480 key_comp() 485 key_compare 480, 485 key_type 480 keyword 793– 794 and 829 and_eq 829 bitand 829 bitor 829 compl 829 not 829 not_eq 829 or 829 or_eq 829 xor 829 xor_eq 829 kind of class 765 of container 461 kinds of object 244 Knuth, Donald 713 L L’ , read more..

  • Page - 1003

    – L – Index 893 Liskov substitution 743 Lisp 725 list of operator functions 262 operation 452 <list> 431 List 435 list 54 doubly-linked 470 element access 472 merge() algorithm and 541 merge() stable 470 remove() 472 remove_if() 472 reverse() 472 sort() stable 470 unique() 472 literal ’ , character 73 L’ , wide-character 73 floating-point 74 implementation dependency type of integer 832 read more..

  • Page - 1004

    894 Index – M – count() in 485 element access 482 equal_range() in 485 erase() from 487 find() in 485 insert() into 487 iterator 481 lower_bound() in 485 member type 480 modify a 487 subscripting 482 upper_bound() in 485 use of 774 mapped type, value 55 mapped_type 480 mapping exception 378 Marian 79 masks_array 678 Math_container example 346 mathematical functions, complex 680 functions, standard read more..

  • Page - 1005

    – M – Index 895 memset() 577 merge() 541 algorithm and list 541 stable, list 470 message queue 477 method 310 choosing a design 696 choosing an analysis 696 cookbook 692 design 694 methods, formal 711 min() 544, 658 valarray 664 min_element() of sequence 544 min_exponent 659 min_exponent10 659 minimalism 706 minimize dependency 173 minus - 517 mismatch() 516, 527 missing bad_alloc 823 checking, late read more..

  • Page - 1006

    896 Index – N – selection from 180 std 46 unnamed 177, 200 using 183 naming convention, iterator 511 narrow() 645 n-ary operators 675 national character 829 conventions 649 natural operation 767 NDEBUG 750 negate - 517 nested class 293 function 806 namespace 848 nesting 756 <new> 384, 433, 576 new and array 423 and exception 576 bad_alloc and 384 exception and 367, 369 operator 127 read more..

  • Page - 1007

    – O – Index 897 pure 732 objects array of 250 global 640 oct 626– 627 oct() 634 octal 73 output 626 ODR the one-definition-rule 203 offset, pointer to member and 419 off_type 608, 643 char_traits 581 ofstream 638 old-style function definition 817 one right way 693 one-beyond-last 512 one-definition-rule, ODR the 203 Op 511 open for reading, in 639 for writing, out 639 namespace is 184 read more..

  • Page - 1008

    898 Index – O – of specialization 343 or construction and destruction 414 or_eq keyword 829 organization of I/O system 606 standard library 431 organizational inertia 713 orthogonality, convenience and 431 oseq() example 556 <ostream> 432 and <iostream> 608 ostream 608, 642 << 609 and buffer 642 and iterator 558 and streambuf 642 put() 609 template and 608 write() 609 ostreambuf read more..

  • Page - 1009

    – P – Index 899 partitioning of program 208, 211 passing multidimensional array 839 pattern 709 specialization 342 pbackfail() 647 pbase() 645 pbump() 645 peek() 643 people and machines, language 9 perfection 43 permutation 545 per-object data 573 per-type data 573 phone_book example 52 physical and logical const 231 structure of program 198 placement new 255 new() 576 of object 255 Plane example read more..

  • Page - 1010

    900 Index – P – standard library 516 user-defined 516 prefix code 624 preprocessing directive # 813 presentation as design tool 704 pre-standard implementation 820 prev_permutation() 545 printf() 651 priority queue 478 priority_queue and heap 479 heap and 543 implementation 478 pop() of 478 push() of 478 top() of 478 private class member 225 member of base class 305 private 402 base 405, 742 read more..

  • Page - 1011

    – P – Index 901 and realloc() 451 push_front() 55, 472 push_heap() 543 put area 645 to, << 607 put() , ostream 609 putback() 643 pword() 650 Q qsort() 158, 546 and exception 382 quadratic time 464 qualification :: , explicit 847 qualified name, namespace 169 qualifier, template as 858 quality 717 queue deque , double-ended 474 priority 478 <queue> 431 queue back() of 476 front() of 476 read more..

  • Page - 1012

    902 Index – R – relationships between templates 348 relaxation of return type 424 release, resource 364 reliability 383 relops , namespace 468 remainder 661 remove() 536 list 472 remove_copy_if() 536 remove_if() 536 list 472 renaming virtual function 778 rend() 481 basicstring 584 iterator 444 reorganization of class hierarchy 707 replace() 535 in string 595 replace_copy() 535 replace_copy_if() 535 read more..

  • Page - 1013

    – S – Index 903 scientific 626, 628 scientific() 634 scope 278 and overload 151 difference from C 816 global 82, 847 local 82 resolution operator :: 82, 228 scrollbar example 743 search, binary 540, 546 search() 528 search_n() 528 seekdir and beg 643 and cur 643 and end 643 direction of seek seekg() direction of 643 seekoff() seekp() direction of 643 set position 642 seekpos() selecting read more..

  • Page - 1014

    904 Index – S – showpos() 634 shuffle 538 sign extension 831 signal 357 <signal.h> 157, 433 signaling_NaN() 659 signed char 831 type 73 unsigned integer conversion 834 Simula 10, 38 Simula-style container 438 simulation 685, 711 event driven 326 sin() 660 complex 680 valarray 667 single quote \’ 830 sinh() 660 complex 680 valarray 667 Sink iterator 532 size and delete 421 and new 421 of read more..

  • Page - 1015

    – S – Index 905 <stack> 431 Stack example 27 stack implementation 475– 476 overflow 476 pop() of 475 push() of 475 top() of 475 underflow 476 stage analysis 697 design 697 development 697 implementation 697 standard component 698, 714 exception 384 guarantees 827 header 431 include directory 201 libraries 700 library 45, 182 library, C 599 library, adding to 434 library algorithms 64 read more..

  • Page - 1016

    906 Index – S – and character buffer 642 ostream and 642 streamoff 609 streamsize 609 stride() 668 string and const , C-style 90 character 432 format 652 initialization of array by 89 literal 46, 90 size of 147 <string> 48, 432, 580 String example 328 string 48, 582 != 591 + 593 += 592 < 591 << 598 <= 591 = 587 == 591 > 591 >= 591 >> 598 [] on 584 algorithm and read more..

  • Page - 1017

    – S – Index 907 user-defined 286 valarray 663 substitution, Liskov 743 substr() of string 596 substring 596 Substring example 596 subtype 743 subtyping 730, 742 successful large system 709 suffix _copy 533 _if 525 code 624 Sum 514 sum() of valarray 664 summary algorithm 509 container 464 syntax 793 sungetc() 646 superclass 303 and subclass 39 supplying default value 500 support 714 run time 8 read more..

  • Page - 1018

    908 Index – T – variable 244, 254 term, longer 699 terminate() 380 terminate_handler 380 termination 370 program 218 ternary operator 636 test() 494 testing 712 design for 712 this 278 self-reference 230 throw 186, 362, 379 tie() 623 time constant 464 linear 464 logarithmic 464 quadratic 464 <time.h> 431, 433 Tiny 275 tinyness_before 659 to_char_type() , char_traits 581 to_int_type() , char_traits read more..

  • Page - 1019

    – T – Index 909 typeid() 414 bad_typeid and 384 <typeinfo> 384, 415, 433 type_info 414 typename 443, 856 type-safe linkage 198 U uflow() 647 unary operator, user-defined 263 unary_function 515 unary_negate 518 not1() and 522 unbuffered I/O 647 input 642 output 642 uncaught exceptions 380 uncaught_exception() 373 unchecked access 445 undeclared argument 154 #undef 162 undefined behavior 828 enum read more..

  • Page - 1020

    910 Index – U – operator += 264, 268, 281 operator -- 291 operator -> 289 operator = 281 operator and built-in type 265 operator and enum 265 pointer conversion 349 predicate 516 subscripting 286 type 32, 70 type, class 224 type conversion 267, 281 type, input of 621 type, literal of 273 type, output of 612 type, string of 583 unary operator 263 user-supplied comparison 467 uses read more..

  • Page - 1021

    – V – Index 911 value call by 146 default 239 key and 480 mapped type 55 of character 580 of cin 276 of notation 261 return 283 return by 148 return , function 148 semantics 294 value_comp() 485 value_compare 485 value_type 443, 480, 552 basic_string 583 variable constructor for global 252 constructor for local 245 global 200, 228 temporary 244, 254 variably-sized object 243 Vec , range read more..

  • Page - 1022

    912 Index – W – wofstream 638 word 76 working system 709 wostream 608 wostringstream 641 wrapper 781 write through iterator 551 write() , ostream 609 ws 634 wstreambuf 649 wstring 582 wstringbuf 649 wstringstream 641 <wtype.h> 432 X X3J16 11 xalloc() 650 xgetn() 647 xor keyword 829 xor_eq keyword 829 xputn() 647 Y Year 285 Z zero null, 0 88 The C++ Programming Language, Third Edition by Bjarne read more..

Write Your Review