Tải bản đầy đủ

Professional c++, 3rd edition

www.it-ebooks.info


www.it-ebooks.info

ffirs.indd 13

11-08-2014 11:29:09


PROFESSIONAL C++
INTRODUCTION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xli

➤➤PART I

INTRODUCTION TO PROFESSIONAL C++

CHAPTER 1

A Crash Course in C++ and the STL . . . . . . . . . . . . . . . . . . . . . . . . . . 3


CHAPTER 2

Working with Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

CHAPTER 3

Coding with Style. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57

➤➤PART II PROFESSIONAL C++ SOFTWARE DESIGN
CHAPTER 4

Designing Professional C++ Programs . . . . . . . . . . . . . . . . . . . . . . . 79

CHAPTER 5

Designing with Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107

CHAPTER 6

Designing for Reuse. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127

➤➤PART III CODING THE PROFESSIONAL WAY
CHAPTER 7

Gaining Proficiency with Classes╯and Objects. . . . . . . . . . . . . . . . . 143

CHAPTER 8

Mastering Classes and Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . 177

CHAPTER 9

Discovering Inheritance Techniques. . . . . . . . . . . . . . . . . . . . . . . . . 217

CHAPTER 10 C++ Quirks, Oddities, and Incidentals. . . . . . . . . . . . . . . . . . . . . . . 273
CHAPTER 11 Writing Generic Code with Templates. . . . . . . . . . . . . . . . . . . . . . . 315
CHAPTER 12 Demystifying C++ I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
CHAPTER 13 Handling Errors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
CHAPTER 14 Overloading C++ Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
CHAPTER 15 Overview of the C++ Standard Library . . . . . . . . . . . . . . . . . . . . . . 443


CHAPTER 16 Understanding Containers and Iterators. . . . . . . . . . . . . . . . . . . . . 467
CHAPTER 17 Mastering STL Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531
CHAPTER 18 String Localization and Regular Expressions. . . . . . . . . . . . . . . . . . 575
CHAPTER 19 Additional Library Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 601

www.it-ebooks.info

ffirs.indd 1

11-08-2014 11:29:07


➤➤PART IV MASTERING ADVANCED FEATURES OF C++
CHAPTER 20 Customizing and Extending the STL . . . . . . . . . . . . . . . . . . . . . . . . 627
CHAPTER 21 Advanced Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 673
CHAPTER 22 Memory Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 707
CHAPTER 23 Multithreaded Programming with C++ . . . . . . . . . . . . . . . . . . . . . . . 741

➤➤PART V C++ SOFTWARE ENGINEERING
CHAPTER 24 Maximizing Software Engineering Methods. . . . . . . . . . . . . . . . . . 781
CHAPTER 25 Writing Efficient C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 801
CHAPTER 26 Conquering Debugging. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 827
APPENDIX A C++ Interviews. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 863
APPENDIX B Annotated Bibliography. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 885
APPENDIX C Standard Library Header Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 895
INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 903

www.it-ebooks.info

ffirs.indd 2

11-08-2014 11:29:07


Professional
C++

www.it-ebooks.info

ffirs.indd 3

11-08-2014 11:29:07


www.it-ebooks.info

ffirs.indd 4

11-08-2014 11:29:07


PROFESSIONAL

C++
Third Edition

Marc Gregoire

www.it-ebooks.info

ffirs.indd 5

11-08-2014 11:29:08


Professional C++, Third Edition
Published by
John Wiley & Sons, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com

Copyright © 2014 by John Wiley & Sons, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-1-118-85805-9
ISBN: 978-1-118-85806-6 (ebk)
ISBN: 978-1-118-85813-4 (ebk)
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means,
electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108
of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization
through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers,
MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the
Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201)
748-6008, or online at http://www.wiley.com/go/permissions.
Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with
respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including
without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or
promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work
is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional
services. If professional assistance is required, the services of a competent professional person should be sought. Neither
the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is
referred to in this work as a citation and/or a potential source of further information does not mean that the author or the
publisher endorses the information the organization or Web site may provide or recommendations it may make. Further,
readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this
work was written and when it is read.
For general information on our other products and services please contact our Customer Care Department within the
United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with
standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to
media such as a CD or DVD that is not included in the version you purchased, you may download this material
at http://booksupport.wiley.com. For more information about Wiley products, visit www.wiley.com.
Library of Congress Control Number: 2014941048
Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are
trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other
countries, and may not be used without written permission. [Insert third-party trademark information] All other
trademarks are the property of their respective owners. John Wiley & Sons, Inc., is not associated with any product or
vendor mentioned in this book.

www.it-ebooks.info

ffirs.indd 6

11-08-2014 11:29:08


Dedicated to my parents, who are always there for me.
—Marc Gregoire

www.it-ebooks.info

ffirs.indd 7

11-08-2014 11:29:08


www.it-ebooks.info

ffirs.indd 8

11-08-2014 11:29:08


ABOUT THE AUTHOR

MARC GREGOIRE╇ is a software engineer from Belgium. He graduated from the

University of Leuven, Belgium, with a degree in “Burgerlijk ingenieur in de computer
wetenschappen” (equivalent to master of science in engineering in computer science).
The year after, he received the cum laude degree of master in artificial intelligence
at the same university. After his studies, Marc started working for a software
consultancy company called Ordina Belgium. As a consultant, he worked for
Siemens and Nokia Siemens Networks on critical 2G and 3G software running on
Solaris for telecom operators. This required working in international teams stretching from South
America and USA to EMEA and Asia. Now, Marc is working for Nikon Metrology on 3D laser
scanning software.
His main expertise is C/C++, and specifically Microsoft VC++ and the MFC framework. He has
experience in developing C++ programs running 24x7 on Windows and Linux platforms; for
example, KNX/EIB home automation software. Next to C/C++, Marc also likes C# and uses PHP
for creating web pages.
Since April 2007, he received the yearly Microsoft MVP (Most Valuable Professional) award for his
Visual C++ expertise.
Marc is the founder of the Belgian C++ Users Group (www.becpp.org), and a member on the
CodeGuru forum (as Marc G). He maintains a blog on www.nuonsoft.com/blog/, and is passionate
about traveling and gastronomic restaurants.

www.it-ebooks.info

ffirs.indd 9

11-08-2014 11:29:09


ABOUT THE TECHNICAL EDITOR

PETER VAN WEERT╇ is a Belgian software engineer, whose main interest and expertise are
programming languages, algorithms, and data structures.

He received his master of science in computer science summa cum laude with congratulations of
the Board of Examiners from the University of Leuven, Belgium. In 2010, he completed his PhD
at the declarative languages and artificial intelligence research group of the same university. His PhD
research revolved around the efficient compilation of rule based programming languages, mainly to
Java. During his doctoral studies, he was a teaching assistant for courses on object-oriented analysis
and design, Java programming, and declarative programming languages.
Since graduating, Peter has worked for Nikon Metrology on 3D laser scanning and point cloud
inspection software, in C++. In his spare time, he has co-authored two award-winning Windows 8
apps.

www.it-ebooks.info

ffirs.indd 10

11-08-2014 11:29:09


CREDITS
EXECUTIVE EDITOR

VICE PRESIDENT AND EXECUTIVE GROUP
PUBLISHER

Robert Elliott

Richard Swadley
PROJECT EDITOR

Adaobi Obi Tulton

ASSOCIATE PUBLISHER

Jim Minatel
TECHNICAL EDITOR

Peter Van Weert

PROJECT COORDINATOR, COVER

Todd Klemme
PRODUCTION EDITOR

Christine Mugnolo

PROOFREADER

Jennifer Bennett, Word One New York
COPY EDITOR

Mike La Bonne

TECHNICAL PROOFREADER

Michael McLaughlin
MANAGER OF CONTENT DEVELOPMENT
AND ASSEMBLY

INDEXER

Mary Beth Wakefield

Johnna Dinse

DIRECTOR OF COMMUNIT Y MARKETING

COVER DESIGNER

David Mayhew

Wiley

MARKETING MANAGER

COVER IMAGE

Carrie Sherrill

©iStock.com/PLAINVIEW

BUSINESS MANAGER

Amy Knies

www.it-ebooks.info

ffirs.indd 11

11-08-2014 11:29:09


www.it-ebooks.info

ffirs.indd 12

11-08-2014 11:29:09


ACKNOWLEDGMENTS

I THANK THE JOHN WILEY & SONS╇ and Wrox Press editorial and production teams for their

support. Especially, thank you to Robert Elliott, executive editor at Wiley, for giving me a chance to
write this new edition and Adaobi Obi Tulton, project editor, for managing this project.
I also thank the original authors of the first edition, Nicholas A. Solter and Scott J. Kleper, for doing
such a great job on which I could base this new edition.
A very special thank you to my technical editor, Peter Van Weert, for his outstanding technical
review. His many constructive comments and ideas have certainly made this book better. Also thank
you to my technical proofreader, Michael B. McLaughlin, for doing a great job on proofreading the
final manuscript.
Of course, the support and patience of my parents, my brother and his wife were very important in
finishing this book.
Finally, I thank you, as readers, for trying this approach to professional C++ software development.

www.it-ebooks.info

ffirs.indd 13

11-08-2014 11:29:09


www.it-ebooks.info

ffirs.indd 14

11-08-2014 11:29:09


CONTENTS

INTRODUCTION

xli

Part I: INTRODUCTION TO PROFESSIONAL C++
CHAPTER 1: A CRASH COURSE IN C++ AND THE STL

The Basics of C++

3

4

The Obligatory Hello, World
4
Comments4
Preprocessor Directives
5
The main() Function
6
I/O Streams
6
Namespaces7
Variables9
Literals11
Operators11
Types13
Enumerated Types
13
Structs15
Conditionals15
if/else Statements
16
switch Statements
16
The Conditional Operator
17
Logical Evaluation Operators
17
Arrays18
std::array20
Loops20
The while Loop
20
The do/while Loop
21
The for Loop
21
The Range-Based for Loop
21
Functions22
Alternative Function Syntax
23
Function Return Type Deduction
23
Type Inference Part 1
24
The auto Keyword
24
The decltype Keyword
24

www.it-ebooks.info

ftoc.indd 15

11-08-2014 11:29:55


CONTENTS

Those Are the Basics

24

Diving Deeper into C++

25

Pointers and Dynamic Memory
25
The Stack and the Heap
25
Working with Pointers
26
Dynamically Allocated Arrays
27
Null Pointer Constant
28
Smart Pointers
28
References29
Strings in C++
30
Exceptions30
The Many Uses of const
32
const Constants
32
const to Protect Parameters
32
const References
32
Type Inference Part 2
33
decltype(auto)33

C++ as an Object-Oriented Language
Defining a Class

34
34

The Standard Library

36

std::vector36

Your First Useful C++ Program

37

An Employee Records System
37
The Employee Class
38
Employee.h38
Employee.cpp39
EmployeeTest.cpp41
The Database Class
41
Database.h41
Database.cpp42
DatabaseTest.cpp43
The User Interface
44
UserInterface.cpp44
Evaluating the Program
46

Summary46
CHAPTER 2: WORKING WITH STRINGS

Dynamic Strings

47

47

C-Style Strings
String Literals
The C++ string Class

48
50
51

xvi

www.it-ebooks.info

ftoc.indd 16

11-08-2014 11:29:55


CONTENTS

What Is Wrong with C-Style Strings?
Using the string Class
std::string Literals
Numeric Conversions
Raw String Literals
Nonstandard Strings

51
51
53
53
54
55

Summary55
CHAPTER 3: CODING WITH STYLE

57

The Importance of Looking Good

57

Thinking Ahead
Elements of Good Style

58
58

Documenting Your Code

58

Reasons to Write Comments
Commenting to Explain Usage
Commenting to Explain Complicated Code
Commenting to Convey Metainformation
Commenting Styles
Commenting Every Line
Prefix Comments
Fixed-Format Comments
Ad Hoc Comments
Self-Documenting Code
Comments in This Book

58
58
60
61
62
62
64
64
65
66
66

Decomposition66
Decomposition through Refactoring
Decomposition by Design
Decomposition in This Book

67
67
68

Naming68
Choosing a Good Name
68
Naming Conventions
69
Counters69
Prefixes69
Getters and Setters
70
Capitalization70
Namespaced Constants
70
Hungarian Notation
70

Using Language Features with Style

71

Use Constants
Use References Instead of Pointers
Use Custom Exceptions

71
71
72
xvii

www.it-ebooks.info

ftoc.indd 17

11-08-2014 11:29:55


CONTENTS

Formatting72
The Curly Brace Alignment Debate
Coming to Blows over Spaces and Parentheses
Spaces and Tabs

72
74
74

Stylistic Challenges
74
Summary75
Part II: PROFESSIONAL C++ SOFTWARE DESIGN
CHAPTER 4: DESIGNING PROFESSIONAL C++ PROGRAMS

What Is Programming Design?
The Importance of Programming Design
Designing for C++
Two Rules for C++ Design

79

80
80
82
83

Abstraction84
Benefiting from Abstraction
84
Incorporating Abstraction in Your Design
84
Reuse85
Reusing Code
86
Writing Reusable Code
86
Reusing Ideas
87

Reusing Code

87

A Note on Terminology
87
Deciding Whether or Not to Reuse Code
88
Advantages to Reusing Code
88
Disadvantages to Reusing Code
89
Putting It Together to Make a Decision
90
Strategies for Reusing Code
90
Understand the Capabilities and Limitations
90
Understand the Performance
91
Understand Platform Limitations
94
Understand Licensing and Support
94
Know Where to Find Help
94
Prototype95
Bundling Third-Party Applications
95
Open-Source Libraries
96
The Open-Source Movements
96
Finding and Using Open-Source Libraries
96
Guidelines for Using Open-Source Code
97
The C++ Standard Library
97
C Standard Library
97
xviii

www.it-ebooks.info

ftoc.indd 18

11-08-2014 11:29:55


CONTENTS

Deciding Whether or Not to Use the STL

Designing with Patterns and Techniques
Designing a Chess Program

98

98
99

Requirements99
Design Steps
99
Divide the Program into Subsystems
99
Choose Threading Models
101
Specify Class Hierarchies for Each Subsystem
101
Specify Classes, Data Structures, Algorithms, and Patterns for
â•… Each Subsystem
102
Specify Error Handling for Each Subsystem
104

Summary105
CHAPTER 5: DESIGNING WITH OBJECTS

Am I Thinking Procedurally?
The Object-Oriented Philosophy

107

108
108

Classes108
Components109
Properties109
Behaviors110
Bringing It All Together
110

Living in a World of Objects

111

Overobjectification111
Overly General Objects
112

Object Relationships

113

The Has-A Relationship
113
The Is-A Relationship (Inheritance)
114
Inheritance Techniques
115
Polymorphism versus Code Reuse
116
The Fine Line between Has-A and Is-A
116
The Not-A Relationship
119
Hierarchies120
Multiple Inheritance
121
Mixin Classes
122

Abstraction122
Interface versus Implementation
Deciding on an Exposed Interface
Consider the Audience
Consider the Purpose
Consider the Future
Designing a Successful Abstraction

123
123
123
124
125
125

Summary126
xix

www.it-ebooks.info

ftoc.indd 19

11-08-2014 11:29:55


CONTENTS

CHAPTER 6: DESIGNING FOR REUSE

The Reuse Philosophy
How to Design Reusable Code
Use Abstraction
Structure Your Code for Optimal Reuse
Avoid Combining Unrelated or Logically Separate Concepts
Use Templates for Generic Data Structures and Algorithms
Provide Appropriate Checks and Safeguards
Design Usable Interfaces
Design Interfaces That Are Easy to Use
Design General-Purpose Interfaces
Reconciling Generality and Ease of Use
Supply Multiple Interfaces
Make Common Functionality Easy to Use

127

127
128
129
130
130
132
134
135
135
138
139
139
140

Summary140
Part III: CODING THE PROFESSIONAL WAY
CHAPTER 7: G
 AINING PROFICIENCY WITH CLASSES
AND OBJECTS

Introducing the Spreadsheet Example
Writing Classes
Class Definitions
Class Members
Access Control
Order of Declarations
Defining Methods
Accessing Data Members
Calling Other Methods
The this Pointer
Using Objects
Objects on the Stack
Objects on the Heap

Object Life Cycles

143

144
144
144
145
145
147
147
148
148
150
151
151
151

152

Object Creation
Writing Constructors
Using Constructors
Providing Multiple Constructors
Default Constructors
Constructor Initializers

153
153
154
155
156
160

xx

www.it-ebooks.info

ftoc.indd 20

11-08-2014 11:29:55


CONTENTS

Copy Constructors
Initializer-List Constructors
In-Class Member Initializers
Delegating Constructors
Summary of Compiler-Generated Constructors
Object Destruction
Assigning to Objects
Declaring an Assignment Operator
Defining an Assignment Operator
Explicitly Defaulted and Deleted Assignment Operator
Distinguishing Copying from Assignment
Objects as Return Values
Copy Constructors and Object Members

162
165
167
167
168
169
170
171
172
173
173
173
174

Summary175
CHAPTER 8: MASTERING CLASSES AND OBJECTS

Dynamic Memory Allocation in Objects
The Spreadsheet Class
Freeing Memory with Destructors
Handling Copying and Assignment
The Spreadsheet Copy Constructor
The Spreadsheet Assignment Operator
Common Helper Routines for Copy Constructor
â•… and Assignment Operator
Disallowing Assignment and Pass-By-Value

Different Kinds of Data Members
static Data Members
Accessing static Data Members within Class Methods
Accessing static Data Members Outside Methods
const Data Members
Reference Data Members
const Reference Data Members

More about Methods

177

178
178
180
180
185
185
187
188

188
188
189
190
190
191
192

193

static Methods
const Methods
mutable Data Members
Method Overloading
Default Parameters
Inline Methods

193
194
195
195
197
197

Nested Classes
Enumerated Types Inside Classes

199
201
xxi

www.it-ebooks.info

ftoc.indd 21

11-08-2014 11:29:55


CONTENTS

Friends202
203
Operator Overloading
Example: Implementing Addition for SpreadsheetCells
First Attempt: The add Method
Second Attempt: Overloaded operator+ as a Method
Third Attempt: Global operator+
Overloading Arithmetic Operators
Overloading the Arithmetic Shorthand Operators
Overloading Comparison Operators
Building Types with Operator Overloading

Building Stable Interfaces
Using Interface and Implementation Classes

203
203
204
206
207
208
210
211

212
212

Summary215
CHAPTER 9: DISCOVERING INHERITANCE TECHNIQUES

Building Classes with Inheritance
Extending Classes
A Client’s View of Inheritance
A Derived Class’s View of Inheritance
Preventing Inheritance
Overriding Methods
How I Learned to Stop Worrying and Make Everything virtual
Syntax for Overriding a Method
A Client’s View of Overridden Methods
Preventing Overriding

Inheritance for Reuse

217

218
218
219
220
221
222
222
223
223
225

225

The WeatherPrediction Class
Adding Functionality in a Derived Class
Replacing Functionality in a Derived Class

Respect Your Parents

225
226
228

229

Parent Constructors
Parent Destructors
Referring to Parent Names
Casting Up and Down

229
230
232
235

Inheritance for Polymorphism

236

Return of the Spreadsheet
Designing the Polymorphic Spreadsheet Cell
The Spreadsheet Cell Base Class
A First Attempt
Pure Virtual Methods and Abstract Base Classes
Base Class Source Code

236
237
237
238
238
239

xxii

www.it-ebooks.info

ftoc.indd 22

11-08-2014 11:29:55


CONTENTS

The Individual Derived Classes
String Spreadsheet Cell Class Definition
String Spreadsheet Cell Implementation
Double Spreadsheet Cell Class Definition and Implementation
Leveraging Polymorphism
Future Considerations

Multiple Inheritance

239
240
240
241
242
243

244

Inheriting from Multiple Classes
Naming Collisions and Ambiguous Base Classes
Name Ambiguity
Ambiguous Base Classes
Uses for Multiple Inheritance

Interesting and Obscure Inheritance Issues
Changing the Overridden Method’s Characteristics
Changing the Method Return Type
Changing the Method Parameters
Inherited Constructors
Special Cases in Overriding Methods
The Base Class Method Is static
The Base Class Method Is Overloaded
The Base Class Method Is private or protected
The Base Class Method Has Default Arguments
The Base Class Method Has a Different Access Level
Copy Constructors and Assignment Operator in Derived Classes
The Truth about virtual
Hiding Instead of Overriding
How virtual Is Implemented
The Justification for virtual
The Need for virtual Destructors
Run-Time Type Facilities
Non-Public Inheritance
Virtual Base Classes

244
246
246
247
248

249
249
249
250
253
256
257
258
259
260
261
264
265
265
266
267
267
268
270
270

Summary271
CHAPTER 10: C++ QUIRKS, ODDITIES, AND INCIDENTALS

273

References274
Reference Variables
Modifying References
References to Pointers and Pointers to References
Reference Data Members
Reference Parameters

274
275
275
276
276
xxiii

www.it-ebooks.info

ftoc.indd 23

11-08-2014 11:29:56


Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay

×