introduction xxv - wiley india xxv part i: ... reusing code 57 ... chapter 5: coding with style 111...

16
CONTENTS INTRODUCTION xxv PART I: INTRODUCTION TO PROFESSIONAL C++ CHAPTER 1: A CRASH COURSE IN C++ 3 The Basics of C++ 3 The Obligatory Hello, World 4 Namespaces 7 Variables 8 Operators 11 Types 13 Conditionals 16 Loops 19 Arrays 20 Functions 22 Those Are the Basics 24 Diving Deeper into C++ 24 Pointers and Dynamic Memory 24 Strings in C++ 28 References 29 Exceptions 30 The Many Uses of const 31 C++ as an Object-Oriented Language 33 Declaring a Class 33 The Standard Library 35 Your First Useful C++ Program 37 An Employee Records System 37 The Employee Class 37 The Database Class 41 The User Interface 44 Evaluating the Program 47 Summary 47 CHAPTER 2: DESIGNING PROFESSIONAL C++ PROGRAMS 49 What Is Programming Design? 50 The Importance of Programming Design 50 What’s Different about C++ Design? 52 Two Rules for C++ Design 53 Abstraction 54 Reuse 55 COPYRIGHTED MATERIAL

Upload: buithu

Post on 04-Jul-2018

215 views

Category:

Documents


0 download

TRANSCRIPT

CONTENTS

INTRODUCTION xxv

PART I: INTRODUCTION TO PROFESSIONAL C++

CHAPTER 1: A CRASH COURSE IN C++ 3

The Basics of C++ 3

The Obligatory Hello, World 4

Namespaces 7

Variables 8

Operators 11

Types 13

Conditionals 16

Loops 19

Arrays 20

Functions 22

Those Are the Basics 24

Diving Deeper into C++ 24

Pointers and Dynamic Memory 24

Strings in C++ 28

References 29

Exceptions 30

The Many Uses of const 31

C++ as an Object-Oriented Language 33

Declaring a Class 33

The Standard Library 35

Your First Useful C++ Program 37

An Employee Records System 37

The Employee Class 37

The Database Class 41

The User Interface 44

Evaluating the Program 47

Summary 47

CHAPTER 2: DESIGNING PROFESSIONAL C++ PROGRAMS 49

What Is Programming Design? 50

The Importance of Programming Design 50

What’s Diff erent about C++ Design? 52

Two Rules for C++ Design 53

Abstraction 54

Reuse 55

ftoc.indd ixftoc.indd ix 8/29/11 9:07:10 AM8/29/11 9:07:10 AM

COPYRIG

HTED M

ATERIAL

x

Reusing Code 57

A Note on Terminology 57

Deciding Whether or Not to Reuse Code 58

Strategies for Reusing Code 60

Bundling Third-Party Applications 65

Open-Source Libraries 66

The C++ Standard Library 67

Designing with Patterns and Techniques 68

Designing a Chess Program 69

Requirements 69

Design Steps 69

Summary 75

CHAPTER 3: DESIGNING WITH OBJECTS 77

Am I Thinking Procedurally? 78

The Object-Oriented Philosophy 78

Classes 78

Components 79

Properties 79

Behaviors 80

Bringing It All Together 80

Living in a World of Objects 81

Overobjectifi cation 81

Overly General Objects 82

Object Relationships 83

The Has-A Relationship 83

The Is-A Relationship (Inheritance) 84

The Fine Line between Has-A and Is-A 86

The Not-A Relationship 89

Hierarchies 90

Multiple Inheritance 91

Mix-in Classes 92

Abstraction 92

Interface versus Implementation 93

Deciding on an Exposed Interface 93

Designing a Successful Abstraction 95

Summary 96

CHAPTER 4: DESIGNING FOR REUSE 97

The Reuse Philosophy 97

How to Design Reusable Code 98

Use Abstraction 99

Structure Your Code for Optimal Reuse 100

Design Usable Interfaces 104

Reconciling Generality and Ease of Use 109

Summary 110

CONTENTS

ftoc.indd xftoc.indd x 8/29/11 9:07:11 AM8/29/11 9:07:11 AM

xi

CHAPTER 5: CODING WITH STYLE 111

The Importance of Looking Good 111

Thinking Ahead 112

Elements of Good Style 112

Documenting Your Code 112

Reasons to Write Comments 112

Commenting Styles 116

Comments in This Book 120

Decomposition 120

Decomposition through Refactoring 121

Decomposition by Design 121

Decomposition in This Book 122

Naming 122

Choosing a Good Name 122

Naming Conventions 123

Using Language Features with Style 125

Use Constants 125

Use References Instead of Pointers 125

Use Custom Exceptions 126

Formatting 126

The Curly Brace Alignment Debate 126

Coming to Blows over Spaces and Parentheses 128

Spaces and Tabs 128

Stylistic Challenges 128

Summary 129

PART II: C++ CODING THE PROFESSIONAL WAY

CHAPTER 6: GAINING PROFICIENCY WITH CLASSES AND OBJECTS 133

Introducing the Spreadsheet Example 134

Writing Classes 134

Class Defi nitions 134

Defi ning Methods 137

Using Objects 141

Object Life Cycles 142

Object Creation 143

Object Destruction 160

Assigning to Objects 162

Distinguishing Copying from Assignment 165

Summary 167

CHAPTER 7: MASTERING CLASSES AND OBJECTS 169

Dynamic Memory Allocation in Objects 169

The Spreadsheet Class 170

CONTENTS

ftoc.indd xiftoc.indd xi 8/29/11 9:07:11 AM8/29/11 9:07:11 AM

xii

Freeing Memory with Destructors 172

Handling Copying and Assignment 172

Diff erent Kinds of Data Members 181

static Data Members 181

const Data Members 183

Reference Data Members 184

const Reference Data Members 185

More about Methods 186

static Methods 186

const Methods 186

Method Overloading 188

Default Parameters 190

Inline Methods 191

Nested Classes 192

Enumerated Types Inside Classes 194

Friends 195

Operator Overloading 197

Example: Implementing Addition for SpreadsheetCells 197

Overloading Arithmetic Operators 202

Overloading Comparison Operators 204

Building Types with Operator Overloading 206

Building Stable Interfaces 206

Using Interface and Implementation Classes 206

Summary 210

CHAPTER 8: DISCOVERING INHERITANCE TECHNIQUES 211

Building Classes with Inheritance 211

Extending Classes 212

Overriding Methods 215

Inheritance for Reuse 219

The WeatherPrediction Class 219

Adding Functionality in a Subclass 220

Replacing Functionality in a Subclass 222

Respect Your Parents 223

Parent Constructors 223

Parent Destructors 224

Referring to Parent Names 226

Casting Up and Down 229

Inheritance for Polymorphism 230

Return of the Spreadsheet 230

Designing the Polymorphic Spreadsheet Cell 231

The Spreadsheet Cell Base Class 231

The Individual Subclasses 233

Leveraging Polymorphism 236

Future Considerations 237

CONTENTS

ftoc.indd xiiftoc.indd xii 8/29/11 9:07:12 AM8/29/11 9:07:12 AM

xiii

Multiple Inheritance 239

Inheriting from Multiple Classes 239

Naming Collisions and Ambiguous Base Classes 240

Interesting and Obscure Inheritance Issues 243

Changing the Overridden Method’s Characteristics 243

Inherited Constructors 247

Special Cases in Overriding Methods 251

Copy Constructors and the Equals Operator in Subclasses 258

The Truth about virtual 259

Run Time Type Facilities 263

Non-Public Inheritance 264

Virtual Base Classes 265

Summary 266

CHAPTER 9: UNDERSTANDING C++ QUIRKS AND ODDITIES 267

References 268

Reference Variables 268

Reference Data Members 271

Reference Parameters 271

Reference Return Values 273

Deciding between References and Pointers 273

Rvalue References 277

Keyword Confusion 282

The const Keyword 282

The static Keyword 288

Order of Initialization of Nonlocal Variables 292

Types and Casts 292

typedefs 292

typedefs for Function Pointers 294

Type Aliases 295

Casts 296

Scope Resolution 300

C++11 301

Uniform Initialization 302

Alternative Function Syntax 304

Null Pointer Constant 304

Angle Brackets 305

Initializer Lists 306

Explicit Conversion Operators 306

Attributes 308

User Defi ned Literals 308

Header Files 310

C Utilities 312

Variable-Length Argument Lists 312

Preprocessor Macros 314

Summary 316

CONTENTS

ftoc.indd xiiiftoc.indd xiii 8/29/11 9:07:12 AM8/29/11 9:07:12 AM

xiv

CHAPTER 10: HANDLING ERRORS 317

Errors and Exceptions 317

What Are Exceptions, Anyway? 318

Why Exceptions in C++ Are a Good Thing 318

Why Exceptions in C++ Are a Bad Thing 320

Our Recommendation 320

Exception Mechanics 320

Throwing and Catching Exceptions 321

Exception Types 324

Throwing and Catching Multiple Exceptions 326

Uncaught Exceptions 329

Throw Lists 331

Exceptions and Polymorphism 336

The Standard Exception Hierarchy 336

Catching Exceptions in a Class Hierarchy 337

Writing Your Own Exception Classes 339

Nested Exceptions 342

Stack Unwinding and Cleanup 344

Use Smart Pointers 346

Catch, Cleanup, and Rethrow 346

Common Error-Handling Issues 347

Memory Allocation Errors 347

Errors in Constructors 350

Function-Try-Blocks for Constructors 352

Errors in Destructors 354

Putting It All Together 355

Summary 359

CHAPTER 11: DELVING INTO THE STANDARD LIBRARY 361

Coding Principles 362

Use of Templates 362

Use of Operator Overloading 366

Overview of the C++ Standard Library 366

Strings 366

I/O Streams 366

Localization 367

Smart Pointers 367

Exceptions 367

Mathematical Utilities 368

Time Utilities 368

Random Numbers 368

Compile-Time Rational Arithmetic 369

Tuples 369

Regular Expressions 369

The Standard Template Library 369

CONTENTS

ftoc.indd xivftoc.indd xiv 8/29/11 9:07:12 AM8/29/11 9:07:12 AM

xv

STL Algorithms 376

What’s Missing from the STL 384

Summary 384

CHAPTER 12: UNDERSTANDING CONTAINERS AND ITERATORS 385

Containers Overview 386

Requirements on Elements 387

Exceptions and Error Checking 388

Iterators 388

C++11 Changes 391

Sequential Containers 393

vector 393

The vector<bool> Specialization 412

deque 413

list 413

array 418

forward_list 418

Container Adapters 421

queue 421

priority_queue 424

stack 427

Associative Containers 428

The pair Utility Class 428

map 430

multimap 438

set 441

multiset 444

Unordered Associative Containers/Hash Tables 444

Hash Functions 444

unordered_map 445

unordered_map Example: Phone Book 448

unordered_multimap 449

unordered_set/unordered_multiset 449

Other Containers 450

Standard C-Style Arrays 450

strings 451

Streams 451

bitset 452

Summary 456

CHAPTER 13: MASTERING STL ALGORITHMS 457

Overview of Algorithms 457

The fi nd and fi nd_if Algorithms 458

The accumulate Algorithms 461

C++11 Move Semantics with Algorithms 462

CONTENTS

ftoc.indd xvftoc.indd xv 8/29/11 9:07:12 AM8/29/11 9:07:12 AM

xvi

Lambda Expressions 463

Syntax 463

Capture Block 465

Lambda Expressions as Return Type 465

Lambda Expressions as Parameters 467

Examples 467

Function Objects 469

Arithmetic Function Objects 470

Comparison Function Objects 471

Logical Function Objects 472

Bitwise Function Objects 473

Function Object Adapters 473

Writing Your Own Function Objects 480

Algorithm Details 481

Utility Algorithms 482

Non-Modifying Algorithms 483

Modifying Algorithms 490

Sorting Algorithms 499

Set Algorithms 501

Algorithms Example: Auditing Voter Registrations 503

The Voter Registration Audit Problem Statement 503

The auditVoterRolls Function 504

The getDuplicates Function 505

Testing the auditVoterRolls Function 506

Summary 507

CHAPTER 14: USING STRINGS AND REGULAR EXPRESSIONS 509

Dynamic Strings 510

C-Style Strings 510

String Literals 512

The C++ string Class 513

Raw String Literals 516

Localization 517

Localizing String Literals 518

Wide Characters 518

Non-Western Character Sets 519

Locales and Facets 521

Regular Expressions 523

ECMAScript Syntax 524

The regex Library 530

regex_match() 531

regex_search() 534

regex_iterator 536

regex_token_iterator 537

regex_replace() 540

Summary 543

CONTENTS

ftoc.indd xviftoc.indd xvi 8/29/11 9:07:13 AM8/29/11 9:07:13 AM

xvii

CHAPTER 15: DEMYSTIFYING C++ I/O 545

Using Streams 546

What Is a Stream, Anyway? 546

Stream Sources and Destinations 547

Output with Streams 547

Input with Streams 552

Input and Output with Objects 559

String Streams 560

File Streams 562

Jumping around with seek() and tell() 563

Linking Streams Together 565

Bidirectional I/O 566

Summary 567

CHAPTER 16: ADDITIONAL LIBRARY UTILITIES 569

std::function 569

Ratios 571

The Chrono Library 574

Duration 574

Clock 578

Time Point 580

Random Number Generation 581

Random Number Engines 582

Random Number Engine Adapters 584

Predefi ned Engines and Engine Adapters 584

Generating Random Numbers 585

Random Number Distributions 587

Tuples 590

Summary 594

CHAPTER 17: CUSTOMIZING AND EXTENDING THE STL 595

Allocators 596

Iterator Adapters 596

Reverse Iterators 596

Stream Iterators 598

Insert Iterators 599

Move Iterators 600

Extending the STL 602

Why Extend the STL? 602

Writing an STL Algorithm 602

Writing an STL Container 605

Summary 641

CONTENTS

ftoc.indd xviiftoc.indd xvii 8/29/11 9:07:13 AM8/29/11 9:07:13 AM

xviii

PART III: MASTERING ADVANCED FEATURES OF C++

CHAPTER 18: OVERLOADING C++ OPERATORS 645

Overview of Operator Overloading 646

Why Overload Operators? 646

Limitations to Operator Overloading 646

Choices in Operator Overloading 647

Operators You Shouldn’t Overload 649

Summary of Overloadable Operators 650

Rvalue References 653

Overloading the Arithmetic Operators 654

Overloading Unary Minus and Unary Plus 654

Overloading Increment and Decrement 655

Overloading the Bitwise and Binary Logical Operators 656

Overloading the Insertion and Extraction Operators 657

Overloading the Subscripting Operator 659

Providing Read-Only Access with operator[] 662

Non-Integral Array Indices 663

Overloading the Function Call Operator 664

Overloading the Dereferencing Operators 666

Implementing operator* 667

Implementing operator-> 668

What in the World Is operator ->* ? 669

Writing Conversion Operators 669

Ambiguity Problems with Conversion Operators 671

Conversions for Boolean Expressions 672

Overloading the Memory Allocation and Deallocation Operators 675

How new and delete Really Work 675

Overloading operator new and operator delete 677

Overloading operator new and operator delete with

Extra Parameters 679

Explicitly Deleting/Defaulting operator new and operator delete 681

Summary 682

CHAPTER 19: WRITING GENERIC CODE WITH TEMPLATES 683

Overview of Templates 684

Class Templates 684

Writing a Class Template 685

How the Compiler Processes Templates 693

Distributing Template Code between Files 694

Template Parameters 695

Method Templates 698

Template Class Specialization 703

Subclassing Template Classes 706

CONTENTS

ftoc.indd xviiiftoc.indd xviii 8/29/11 9:07:14 AM8/29/11 9:07:14 AM

xix

Inheritance versus Specialization 708

Template Aliases 708

Alternative Function Syntax 709

Function Templates 710

Function Template Specialization 711

Function Template Overloading 712

Friend Function Templates of Class Templates 713

Summary 714

CHAPTER 20: ADVANCED TEMPLATES 715

More about Template Parameters 715

More about Template Type Parameters 715

Introducing Template Template Parameters 719

More about Non-Type Template Parameters 721

Template Class Partial Specialization 724

Another Form of Partial Specialization 726

Emulating Function Partial Specialization with Overloading 729

More on Deduction 730

Template Recursion 731

An N-Dimensional Grid: First Attempt 731

A Real N-Dimensional Grid 733

Type Inference 738

The auto Keyword 738

The decltype Keyword 739

auto and decltype with Templates 739

Variadic Templates 742

Type-Safe Variable-Length Argument Lists 743

Variable Number of Mix-In Classes 745

Metaprogramming 746

Factorial at Compile Time 746

Loop Unrolling 747

Printing Tuples 749

Type Traits 751

Conclusion 757

Summary 757

CHAPTER 21: EFFECTIVE MEMORY MANAGEMENT 759

Working with Dynamic Memory 759

How to Picture Memory 760

Allocation and Deallocation 761

Arrays 763

Working with Pointers 769

Array-Pointer Duality 771

Arrays Are Pointers! 772

Not All Pointers Are Arrays! 773

CONTENTS

ftoc.indd xixftoc.indd xix 8/29/11 9:07:14 AM8/29/11 9:07:14 AM

xx

Low-Level Memory Operations 774

Pointer Arithmetic 774

Custom Memory Management 775

Garbage Collection 775

Object Pools 776

Function Pointers 776

Pointers to Methods and Members 778

Smart Pointers 779

The Old Deprecated auto_ptr 780

The New C++11 Smart Pointers 781

Writing Your Own Smart Pointer Class 784

Common Memory Pitfalls 790

Underallocating Strings 790

Memory Leaks 791

Double-Deleting and Invalid Pointers 794

Accessing Out-of-Bounds Memory 795

Summary 796

CHAPTER 22: MULTITHREADED PROGRAMMING WITH C++ 797

Introduction 798

Race Conditions and Deadlocks 799

Atomic Operations Library 802

Atomic Type Example 803

Atomic Operations 805

Threads 806

Thread with Function Pointer 806

Thread with Function Object 808

Thread with Lambda 810

Thread with Member Function 811

Thread Local Storage 811

Cancelling Threads 812

Retrieving Results from Threads 812

Copying and Rethrowing Exceptions 812

Mutual Exclusion 815

Mutex Classes 815

Locks 817

std::call_once 819

Mutex Usage Examples 820

Condition Variables 823

Futures 825

Example: Multithreaded Logger Class 827

Thread Pools 833

Threading Design and Best Practices 834

Summary 835

CONTENTS

ftoc.indd xxftoc.indd xx 8/29/11 9:07:15 AM8/29/11 9:07:15 AM

xxi

PART IV: C++ SOFTWARE ENGINEERING

CHAPTER 23: MAXIMIZING SOFTWARE ENGINEERING METHODS 839

The Need for Process 840

Software Life Cycle Models 841

The Stagewise Model and Waterfall Model 841

The Spiral Model 843

The Rational Unifi ed Process 845

Software Engineering Methodologies 847

Agile 847

Scrum 848

Extreme Programming (XP) 850

Software Triage 854

Building Your Own Process and Methodology 854

Be Open to New Ideas 854

Bring New Ideas to the Table 855

Recognize What Works and What Doesn’t Work 855

Don’t Be a Renegade 855

Source Code Control 855

Summary 857

CHAPTER 24: WRITING EFFICIENT C++ 859

Overview of Performance and Effi ciency 859

Two Approaches to Effi ciency 860

Two Kinds of Programs 860

Is C++ an Ineffi cient Language? 860

Language-Level Effi ciency 861

Handle Objects Effi ciently 862

Use Inline Methods and Functions 866

Design-Level Effi ciency 866

Cache as Much as Possible 866

Use Object Pools 867

Profi ling 871

Profi ling Example with gprof 872

Profi ling Example with Visual C++ 2010 880

Summary 882

CHAPTER 25: DEVELOPING CROSS-PLATFORM AND CROSS-LANGUAGE APPLICATIONS 883

Cross-Platform Development 884

Architecture Issues 884

Implementation Issues 886

Platform-Specifi c Features 888

CONTENTS

ftoc.indd xxiftoc.indd xxi 8/29/11 9:07:15 AM8/29/11 9:07:15 AM

xxii

Cross-Language Development 888

Mixing C and C++ 889

Shifting Paradigms 889

Linking with C Code 892

Mixing C# with C++ 894

Mixing Java and C++ with JNI 896

Mixing C++ with Perl and Shell Scripts 898

Mixing C++ with Assembly Code 902

Summary 903

CHAPTER 26: BECOMING ADEPT AT TESTING 905

Quality Control 906

Whose Responsibility Is Testing? 906

The Life Cycle of a Bug 906

Bug-Tracking Tools 907

Unit Testing 909

Approaches to Unit Testing 909

The Unit Testing Process 910

Unit Testing in Action 914

Higher-Level Testing 921

Integration Tests 921

System Tests 923

Regression Tests 923

Tips for Successful Testing 924

Summary 925

CHAPTER 27: CONQUERING DEBUGGING 927

The Fundamental Law of Debugging 928

Bug Taxonomies 928

Avoiding Bugs 928

Planning for Bugs 929

Error Logging 929

Debug Traces 930

Asserts 943

Static Asserts 944

Debugging Techniques 945

Reproducing Bugs 945

Debugging Reproducible Bugs 946

Debugging Nonreproducible Bugs 947

Debugging Memory Problems 948

Debugging Multithreaded Programs 952

Debugging Example: Article Citations 953

Lessons from the ArticleCitations Example 966

Summary 966

CONTENTS

ftoc.indd xxiiftoc.indd xxii 8/29/11 9:07:15 AM8/29/11 9:07:15 AM

xxiii

CHAPTER 28: INCORPORATING DESIGN TECHNIQUES AND FRAMEWORKS 967

“I Can Never Remember How to . . .” 968

. . . Write a Class 968

. . . Subclass an Existing Class 969

. . . Throw and Catch Exceptions 970

. . . Read from a File 971

. . . Write to a File 971

. . . Write a Template Class 972

There Must Be a Better Way 973

Double Dispatch 973

Mix-In Classes 979

Object-Oriented Frameworks 981

Working with Frameworks 982

The Model-View-Controller Paradigm 982

Summary 983

CHAPTER 29: APPLYING DESIGN PATTERNS 985

The Iterator Pattern 986

The Singleton Pattern 987

Example: A Logging Mechanism 987

Implementation of a Singleton 987

Using a Singleton 991

Singletons and Multithreading 992

The Factory Pattern 995

Example: A Car Factory Simulation 995

Implementation of a Factory 996

Using a Factory 998

Other Uses of Factories 1000

The Proxy Pattern 1000

Example: Hiding Network Connectivity Issues 1000

Implementation of a Proxy 1001

Using a Proxy 1002

The Adapter Pattern 1002

Example: Adapting a Logger Class 1002

Implementation of an Adapter 1003

Using an Adapter 1004

The Decorator Pattern 1004

Example: Defi ning Styles in Web Pages 1004

Implementation of a Decorator 1005

Using a Decorator 1006

The Chain of Responsibility Pattern 1007

Example: Event Handling 1008

Implementation of a Chain of Responsibility 1008

Using a Chain of Responsibility 1009

CONTENTS

ftoc.indd xxiiiftoc.indd xxiii 8/29/11 9:07:16 AM8/29/11 9:07:16 AM

xxiv

The Observer Pattern 1009

Example: Event Handling 1009

Implementation of an Observer 1009

Using an Observer 1011

Summary 1012

APPENDIX A: C++ INTERVIEWS 1013

APPENDIX B: ANNOTATED BIBLIOGRAPHY 1035

APPENDIX C: STANDARD LIBRARY HEADER FILES 1045

INDEX 1053

CONTENTS

ftoc.indd xxivftoc.indd xxiv 8/29/11 9:07:16 AM8/29/11 9:07:16 AM