Nicht aus der Schweiz? Besuchen Sie lehmanns.de

Professional C++ (eBook)

eBook Download: PDF
2023 | 6. Auflage
1379 Seiten
Wiley (Verlag)
978-1-394-19319-6 (ISBN)

Lese- und Medienproben

Professional C++ -  Marc Gregoire
Systemvoraussetzungen
53,99 inkl. MwSt
(CHF 52,75)
Der eBook-Verkauf erfolgt durch die Lehmanns Media GmbH (Berlin) zum Preis in Euro inkl. MwSt.
  • Download sofort lieferbar
  • Zahlungsarten anzeigen

Expand your C++ toolkit quickly and efficiently with this advanced resource

In the newly revised sixth edition of Professional C++, veteran software engineer and developer Marc Gregoire delivers yet another volume that raises the bar for advanced programming manuals. Covering the major new revisions contained in the new C++ standard codenamed C++23, the book offers case studies with working code that's been tested in Windows and Linux.

The leading resource for dedicated and knowledgeable professionals seeking to advance their C++ skills, this book provides resources that help readers:

  • Maximize C++ capabilities with effective design solutions
  • Master little-known elements and learn what practices to avoid
  • Adopt new workarounds and testing/debugging best practices
  • Use real-world program segments in your own applications

C++ is a complex and unforgiving language. Professional C++, 6th Edition, allows dedicated practitioners to remain current and abreast of the latest developments and advances.

MARC GREGOIRE is a software engineer and developer of C/C++ applications for both Windows and Linux. He is a Microsoft MVP, the founder of the Belgian C++ users group, and is currently working on X-ray, CT, and 3-D geometric inspection software for Nikon Metrology. He previously worked on critical 2G and 3G telecom software for Siemens and Nokia Siemens Networks. Marc is the author of Professional C++ 2nd, 3rd, 4th, and 5th editions, co-author of C++ Standard Library Quick Reference, technical editor on numerous books and articles, and maintains a blog at nuonsoft.com/blog.

MARC GREGOIRE is a software engineer and developer of C/C++ applications for both Windows and Linux. He is a Microsoft MVP, the founder of the Belgian C++ users group, and is currently working on X-ray, CT, and 3-D geometric inspection software for Nikon Metrology. He previously worked on critical 2G and 3G telecom software for Siemens and Nokia Siemens Networks. Marc is the author of Professional C++ 2nd, 3rd, 4th, and 5th editions, co-author of C++ Standard Library Quick Reference, technical editor on numerous books and articles, and maintains a blog at nuonsoft.com/blog.

Cover 1
Title Page 3
Copyright Page 4
About the Author 6
Contents 9
Introduction 43
Who This Book Is For 43
What This Book Covers 44
How This Book is Structured 45
Conventions 46
What You Need to Use This Book 47
Any C++ Compiler 47
Example: Microsoft Visual C++ 2022 48
Example: GCC 48
C++23’s Support for Printing Ranges 49
Reader Support for This Book 50
Companion Download Files 50
How to Contact the Publisher 50
How to Contact the Author 51
Part I Introduction to Professional C++ 53
Chapter 1 A Crash Course in C++ and the Standard Library 55
C++ Crash Course 56
The Obligatory “Hello, World” Program 56
Comments 57
Importing Modules 57
How the Compiler Processes Your Source Code 58
Preprocessor Directives 58
The main() Function 59
Printing Text 59
I/O Streams 59
Returning from a Function 61
Namespaces 61
Nested Namespace 63
Namespace Alias 63
Literals 63
Variables 64
Numerical Limits 67
Zero Initialization 67
Casting 68
Floating-Point Numbers 68
Operators 70
Enumerations 73
Old-Style Enumerations 74
Structs 75
Conditional Statements 76
if/else Statements 76
switch Statements 77
The Conditional Operator 79
Logical Evaluation Operators 79
Three-Way Comparisons 81
Functions 82
Function Return Type Deduction 83
Current Function’s Name 84
Function Overloading 84
Attributes 84
[[nodiscard]] 85
[[maybe_unused]] 85
[[noreturn]] 86
[[deprecated]] 86
[[likely]] and [[unlikely]] 87
[[assume]] 87
C-Style Arrays 88
std::array 89
std::vector 90
std::pair 91
std::optional 92
Structured Bindings 93
Loops 93
The while Loop 93
The do/while Loop 94
The for Loop 94
The Range-Based for Loop 94
Initializer Lists 95
Strings in C++ 95
C++ as an Object-Oriented Language 96
Defining Classes 96
Using Classes 99
Scope Resolution 99
Uniform Initialization 100
Designated Initializers 103
Pointers and Dynamic Memory 104
The Stack and the Free Store 104
Working with Pointers 105
Dynamically Allocated Arrays 106
Null Pointer Constant 107
The Use of const 108
const as a Qualifier for a Type 108
const Member Functions 110
References 111
Reference Variables 111
Reference Data Members 114
Reference Parameters 114
Reference Return Values 117
Deciding Between References and Pointers 117
const_cast() 121
Exceptions 122
Type Aliases 123
typedefs 124
Type Inference 124
The auto Keyword 124
The decltype Keyword 127
The Standard Library 127
Your First Bigger C++ Program 128
An Employee Records System 128
The Employee Class 128
Employee.cppm 128
Employee.cpp 130
EmployeeTest.cpp 131
The Database Class 132
Database.cppm 132
Database.cpp 133
DatabaseTest.cpp 134
The User Interface 134
Evaluating the Program 137
Summary 137
Exercises 137
Chapter 2 Working with Strings and String Views 139
Dynamic Strings 140
C-Style Strings 140
String Literals 142
Raw String Literals 142
The C++ std::string Class 144
What Is Wrong with C-StyleStrings? 144
Using the std::string Class 144
std::string Literals 147
CTAD with std::vector and Strings 148
Numeric Conversions 148
High-Level Numeric Conversions 148
Low-Level Numeric Conversions 150
The std::string_view Class 152
std::string_view and Temporary Strings 154
std::string_view Literals 154
Nonstandard Strings 155
Formatting and Printing Strings 155
Format Strings 156
Argument Indices 157
Printing to Different Destinations 158
Compile-Time Verification of Format Strings 158
Non-Compile-Time Constant Format Strings 158
Handling Errors in Non-Compile-Time Constant Format Strings 159
Format Specifiers 159
width 160
[fill]align 160
sign 161
# 161
type 161
precision 162
0 163
L 163
Formatting Escaped Characters and Strings 163
Formatting Ranges 164
Support for Custom Types 166
Summary 169
Exercises 169
Chapter 3 Coding with Style 171
The Importance of Looking Good 171
Thinking Ahead 172
Elements of Good Style 172
Documenting Your Code 172
Reasons to Write Comments 172
Commenting to Explain Usage 172
Commenting to Explain Complicated Code 174
Commenting to Convey Meta-information 176
Copyright Comment 177
Commenting Styles 177
Commenting Every Line 177
Prefix Comments 178
Fixed-Format Comments 179
Ad Hoc Comments 181
Self-Documenting Code 181
Decomposition 181
Decomposition through Refactoring 182
Decomposition by Design 183
Decomposition in This Book 183
Naming 184
Choosing a Good Name 184
Naming Conventions 185
Counters 185
Prefixes 185
Hungarian Notation 186
Getters and Setters 186
Capitalization 186
Namespaced Constants 186
Using Language Features with Style 187
Use Constants 187
Use References Instead of Pointers 188
Use Custom Exceptions 188
Formatting 189
The Curly Brace Alignment Debate 189
Coming to Blows over Spaces and Parentheses 190
Spaces, Tabs, and Line Breaks 191
Stylistic Challenges 191
Summary 192
Exercises 192
Part II Professional C++ Software Design 195
Chapter 4 Designing Professional C++ Programs 197
What is Programming Design? 198
The Importance of Programming Design 199
Designing For C++ 201
Two Rules for Your Own C++ Designs 202
Abstraction 202
Benefiting from Abstraction 202
Incorporating Abstraction in Your Design 203
Reuse 204
Writing Reusable Code 205
Reusing Designs 205
Reusing Existing Code 206
A Note on Terminology 207
Deciding Whether to Reuse Code or Write It Yourself 208
Advantages to Reusing Code 208
Disadvantages to Reusing Code 209
Putting It Together to Make a Decision 210
Guidelines for Choosing a Library to Reuse 210
Understand the Capabilities and Limitations 210
Understand the Learning Cost 211
Understand the Performance 211
Understand Platform Limitations 214
Understand Licensing 214
Understand Support and Know Where to Find Help 214
Prototype 215
Open-Source Libraries 215
The C++ Standard Library 217
Designing a Chess Program 218
Requirements 218
Design Steps 219
Divide the Program into Subsystems 219
Choose Threading Models 221
Specify Class Hierarchies for Each Subsystem 222
Specify Classes, Data Structures, Algorithms, and Patterns for Each Subsystem 222
Specify Error Handling for Each Subsystem 225
Summary 226
Exercises 227
Chapter 5 Designing with Classes 229
Am I Thinking Procedurally? 230
The Object-Oriented Philosophy 230
Classes 230
Components 231
Properties 231
Behaviors 232
Bringing It All Together 232
Living In a World of Classes 233
Over-Classification 234
Overly General Classes 234
Class Relationships 235
The Has-a Relationship 235
The Is-a Relationship (Inheritance) 236
Inheritance Techniques 237
Polymorphism 238
The Fine Line Between Has-a and Is-a 238
The Not-a Relationship 242
Hierarchies 243
Multiple Inheritance 244
Mixin Classes 245
Summary 246
Exercises 246
Chapter 6 Designing for Reuse 249
The Reuse Philosophy 250
How to Design Reusable Code 250
Use Abstraction 251
Structure Your Code for Optimal Reuse 252
Avoid Combining Unrelated or Logically Separate Concepts 253
Use Templates for Generic Data Structures and Algorithms 255
Provide Appropriate Checks and Safeguards 257
Design for Extensibility 258
Design Usable Interfaces 260
Consider the Audience 260
Consider the Purpose 261
Design Interfaces That Are Easy to Use 262
Design General-Purpose Interfaces 266
Reconciling Generality and Ease of Use 267
Designing a Successful Abstraction 268
The SOLID Principles 268
Summary 269
Exercises 269
Part III C++ Coding the Professional Way 271
Chapter 7 Memory Management 273
Working with Dynamic Memory 274
How to Picture Memory 274
Allocation and Deallocation 275
Using new and delete 275
What About My Good Friend malloc? 276
When Memory Allocation Fails 277
Arrays 277
Arrays of Primitive Types 278
Arrays of Objects 280
Deleting Arrays 280
Multidimensional Arrays 281
Working with Pointers 285
A Mental Model for Pointers 285
Casting with Pointers 286
Array-Pointer Duality 286
Arrays Decay to Pointers 286
Not All Pointers Are Arrays! 288
Low-Level Memory Operations 288
Pointer Arithmetic 288
Custom Memory Management 289
Garbage Collection 290
Object Pools 290
Common Memory Pitfalls 291
Underallocating Data Buffers and Out-of-Bounds Memory Access 291
Memory Leaks 292
Finding and Fixing Memory Leaks in Windows with Visual C++ 293
Finding and Fixing Memory Leaks in Linux with Valgrind 295
Double-Deletion and Invalid Pointers 295
Smart Pointers 296
unique_ptr 297
Creating unique_ptrs 297
Using unique_ptrs 299
unique_ptr and C-StyleArrays 300
Custom Deleters 300
shared_ptr 301
Creating and Using shared_ptrs 301
The Need for Reference Counting 302
Casting a shared_ptr 303
Aliasing 304
weak_ptr 304
Passing to Functions 305
Returning from Functions 305
enable_shared_from_this 306
Interoperability of Smart Pointers with C-Style Functions 307
The Old and Removed auto_ptr 307
Summary 308
Exercises 308
Chapter 8 Gaining Proficiency with Classes and Objects 311
Introducing the Spreadsheet Example 312
Writing Classes 312
Class Definitions 312
Class Members 313
Access Control 313
Order of Declarations 314
In-Class Member Initializers 315
Defining Member Functions 315
Accessing Data Members 316
Calling Other Member Functions 316
Using Objects 317
Objects on the Stack 318
Objects on the Free Store 318
The this Pointer 319
Explicit Object Parameter 320
Understanding Object Life Cycles 321
Object Creation 321
Writing Constructors 322
Using Constructors 322
Providing Multiple Constructors 323
Default Constructors 324
Constructor Initializers aka Ctor-Initializers 328
Copy Constructors 331
Initializer-List Constructors 333
Delegating Constructors 335
Converting Constructors and Explicit Constructors 336
Summary of Compiler-Generated Constructors 337
Object Destruction 338
Assigning to Objects 340
Declaring an Assignment Operator 340
Defining an Assignment Operator 341
Explicitly Defaulted and Deleted Assignment Operator 342
Compiler-Generated Copy Constructor and Copy Assignment Operator 343
Distinguishing Copying from Assignment 343
Objects as Return Values 343
Copy Constructors and Object Members 344
Summary 345
Exercises 345
Chapter 9 Mastering Classes and Objects 347
Friends 348
Dynamic Memory Allocation in Objects 349
The Spreadsheet Class 349
Freeing Memory with Destructors 352
Handling Copying and Assignment 353
The Spreadsheet Copy Constructor 355
The Spreadsheet Assignment Operator 355
Disallowing Assignment and Pass-by-Value 358
Handling Moving with Move Semantics 359
Rvalue References 359
Decay Copy 362
Implementing Move Semantics 362
Testing the Spreadsheet Move Operations 366
Implementing a Swap Function with Move Semantics 368
Using std::move() in Return Statements 369
Optimal Way to Pass Arguments to Functions 370
Rule of Zero 371
More About Member Functions 372
static Member Functions 372
const Member Functions 373
mutable Data Members 374
Member Function Overloading 375
Overloading Based on const 375
Explicitly Deleting Overloads 377
Ref-Qualified Member Functions 377
Inline Member Functions 379
Default Arguments 381
Constexpr and Consteval 382
The constexpr Keyword 382
The consteval Keyword 383
constexpr and consteval Classes 384
Different Kinds of Data Members 385
static Data Members 385
Inline Variables 386
Accessing static Data Members from within Class Member Functions 386
constexpr static Data Members 387
Accessing static Data Members from Outside Class Member Functions 388
Reference Data Members 388
Nested Classes 390
Enumerations Inside Classes 391
Operator Overloading 391
Example: Implementing Addition for SpreadsheetCells 392
First Attempt: The add Member Function 392
Second Attempt: Overloaded operator+ as a Member Function 393
Third Attempt: Global operator+ 394
Overloading Arithmetic Operators 395
Overloading the Arithmetic Shorthand Operators 396
Overloading Comparison Operators 397
Overloading Comparison Operators Before C++20 397
Overloading Comparison Operators Since C++20 399
Compiler-Generated Comparison Operators 400
Building Stable Interfaces 402
Using Interface and Implementation Classes 402
Summary 406
Exercises 406
Chapter 10 Discovering Inheritance Techniques 409
Building Classes with Inheritance 410
Extending Classes 410
A Client’s View of Inheritance 411
A Derived Class’s View of Inheritance 412
Preventing Inheritance 414
Overriding Member Functions 414
The virtual Keyword 414
Syntax for Overriding a Member Function 415
A Client’s View of Overridden Member Functions 415
The override Keyword 417
The Truth about virtual 418
Preventing Overriding 422
Inheritance For Reuse 422
The WeatherPrediction Class 422
Adding Functionality in a Derived Class 423
Replacing Functionality in a Derived Class 425
Respect Your Parents 425
Parent Constructors 425
Parent Destructors 427
virtual Member Function Calls within Constructors and Destructor 428
Referring to Parent Names 429
Casting Up and Down 431
Inheritance for Polymorphism 432
Return of the Spreadsheet 432
Designing the Polymorphic Spreadsheet Cell 433
The SpreadsheetCell Base Class 434
A First Attempt 434
Pure virtual Member Functions and Abstract Base Classes 434
The Individual Derived Classes 435
StringSpreadsheetCell Class Definition 435
StringSpreadsheetCell Implementation 436
DoubleSpreadsheetCell Class Definition and Implementation 436
Leveraging Polymorphism 437
Future Considerations 438
Providing Implementations for Pure virtual Member Functions 440
Multiple Inheritance 440
Inheriting from Multiple Classes 441
Naming Collisions and Ambiguous Base Classes 442
Name Ambiguity 442
Ambiguous Base Classes 443
Uses for Multiple Inheritance 444
Interesting and Obscure Inheritance Issues 444
Changing the Overridden Member Function’s Return Type 445
Adding Overloads of virtual Base Class Member Functions to Derived Classes 448
Inherited Constructors 448
Hiding of Inherited Constructors 449
Inherited Constructors and Multiple Inheritance 450
Initialization of Data Members 451
Special Cases in Overriding Member Functions 452
The Base Class Member Function Is static 452
The Base Class Member Function Is Overloaded 453
The Base Class Member Function Is private 455
The Base Class Member Function Has Default Arguments 456
The Base Class Member Function Has a Different Access Specification 457
Copy Constructors and Assignment Operators in Derived Classes 459
Run-Time Type Facilities 460
Non-public Inheritance 462
Virtual Base Classes 463
Casts 466
static_cast() 466
reinterpret_cast() 467
dynamic_cast() 468
std::bit_cast() 469
Summary of Casts 470
Summary 470
Exercises 471
Chapter 11 Modules, Header Files, and Miscellaneous Topics 473
Modules 474
Unmodularizing Code 475
Standard Named Modules 475
Module Interface Files 475
Module Implementation Files 477
Splitting Interface from Implementation 478
Visibility vs. Reachability 479
Submodules 480
Module Partitions 481
Implementation Partitions 483
Private Module Fragment 484
Header Units 485
Importable Standard Library Headers 486
Preprocessor Directives 488
Preprocessor Macros 489
Linkage 490
Internal Linkage 491
The extern Keyword 492
Header Files 493
One Definition Rule (ODR) 493
Duplicate Definitions 494
Circular Dependencies 494
Querying Existence of Headers 495
Module Import Declarations 495
Feature-Test Macros for Core Language Features 496
The Static Keyword 497
static Data Members and Member Functions 497
static Variables in Functions 497
Order of Initialization of Nonlocal Variables 498
Order of Destruction of Nonlocal Variables 498
C-Style Variable-Length Argument Lists 499
Accessing the Arguments 500
Why You Shouldn’t Use C-Style Variable-Length Argument Lists 500
Summary 501
Exercises 501
Chapter 12 Writing Generic Code with Templates 503
Overview of Templates 504
Class Templates 505
Writing a Class Template 505
Coding Without Templates 505
A Template Grid Class 508
Using the Grid Template 512
How the Compiler Processes Templates 513
Selective/Implicit Instantiation 514
Explicit Instantiation 514
Template Requirements on Types 514
Distributing Template Code Between Files 515
Member Function Definitions in Same File as Class Template Definition 515
Member Function Definitions in Separate File 515
Template Parameters 516
Non-type Template Parameters 516
Default Values for Template Parameters 518
Class Template Argument Deduction 519
Member Function Templates 520
Member Function Templates with Non-type Template Parameters 523
Using Member Function Templates with Explicit Object Parameters to Avoid Code Duplication 525
Class Template Specialization 526
Deriving from Class Templates 529
Inheritance vs. Specialization 530
Alias Templates 531
Function Templates 531
Function Overloads vs. Function Template 533
Function Template Overloading 533
Function Templates as Friends of Class Templates 534
More on Template Type Parameter Deduction 536
Return Type of Function Templates 536
Abbreviated Function Template Syntax 538
Variable Templates 539
Concepts 539
Syntax 540
Constraints Expression 540
Requires Expressions 541
Combining Concept Expressions 543
Predefined Standard Concepts 543
Type-Constrained auto 544
Type Constraints and Function Templates 545
Constraint Subsumption 547
Type Constraints and Class Templates 547
Type Constraints and Class Member Functions 548
Constraint-Based Class Template Specialization and Function Template Overloading 548
Best Practices 549
Summary 550
Exercises 550
Chapter 13 Demystifying C++ I/O 553
Using Streams 554
What Is a Stream, Anyway? 554
Stream Sources and Destinations 556
Output with Streams 556
Output Basics 556
Member Functions of Output Streams 557
Handling Output Errors 558
Output Manipulators 560
Input with Streams 562
Input Basics 562
Handling Input Errors 563
Input Member Functions 564
Input Manipulators 568
Input and Output with Objects 569
Custom Manipulators 571
String Streams 571
Span-Based Streams 573
File Streams 574
Text Mode vs. Binary Mode 575
Jumping Around with seek() and tell() 575
Linking Streams Together 578
Read an Entire File 578
Bidirectional I/O 579
Filesystem Support Library 580
Path 580
Directory Entry 582
Helper Functions 582
Directory Iteration 582
Summary 583
Exercises 584
Chapter 14 Handling Errors 585
Errors and Exceptions 586
What Are Exceptions, Anyway? 586
Why Exceptions in C++ Are a Good Thing 587
Recommendation 588
Exception Mechanics 588
Throwing and Catching Exceptions 589
Exception Types 592
Catching Exception Objects as Reference-to-const 593
Throwing and Catching Multiple Exceptions 593
Matching and const 595
Matching Any Exception 595
Uncaught Exceptions 596
noexcept Specifier 598
noexcept(expression) Specifier 598
noexcept(expression) Operator 598
Throw Lists 599
Exceptions and Polymorphism 599
The Standard Exception Hierarchy 599
Catching Exceptions in a Class Hierarchy 601
Writing Your Own Exception Classes 602
Nested Exceptions 605
Rethrowing Exceptions 607
Stack Unwinding and Cleanup 608
Use Smart Pointers 610
Catch, Cleanup, and Rethrow 610
Source Location 611
Source Location for Logging 612
Automatically Embed a Source Location in Custom Exceptions 612
Stack Trace 613
The Stack Trace Library 613
Automatically Embed a Stack Trace in Custom Exceptions 615
Common Error-Handling Issues 616
Memory Allocation Errors 617
Non-throwing new 617
Customizing Memory Allocation Failure Behavior 618
Errors in Constructors 619
Function-Try-Blocks for Constructors 621
Errors in Destructors 624
Exception Safety Guarantees 625
Summary 625
Exercises 625
Chapter 15 Overloading C++ Operators 629
Overview of Operator Overloading 630
Why Overload Operators? 630
Limitations to Operator Overloading 630
Choices in Operator Overloading 631
Member Function or Global Function 631
Choosing Argument Types 632
Choosing Return Types 633
Choosing Behavior 633
Operators You Shouldn’t Overload 633
Summary of Overloadable Operators 634
Rvalue References 638
Precedence and Associativity 639
Relational Operators 640
Alternative Notation 641
Overloading The Arithmetic Operators 641
Overloading Unary Minus and Unary Plus 641
Overloading Increment and Decrement 642
Overloading the Bitwise and Binary Logical Operators 643
Overloading the Insertion and Extraction Operators 643
Overloading the Subscripting Operator 645
Providing Read-Only Access with operator[] 648
Multidimensional Subscripting Operator 650
Non-integral Array Indices 651
static Subscripting Operator 651
Overloading the Function Call Operator 652
static Function Call Operator 653
Overloading the Dereferencing Operators 654
Implementing operator* 655

What in the World Are operator.* and operator–> *?
Writing Conversion Operators 657
Operator auto 658
Solving Ambiguity Problems with Explicit Conversion Operators 658
Conversions for Boolean Expressions 659
Overloading the Memory Allocation and Deallocation Operators 661
How new and delete Really Work 661
The New-Expression and operator new 661
The Delete-Expression and operator delete 662
Overloading operator new and operator delete 662
Explicitly Deleting or Defaulting operator new and operator delete 665
Overloading operator new and operator delete with Extra Parameters 665
Overloading operator delete with Size of Memory as Parameter 666
Overloading User-Defined Literal Operators 667
Standard Library Literals 667
User-Defined Literals 668
Cooked-Mode Literal Operator 668
Raw-Mode Literal Operator 669
Summary 670
Exercises 670
Chapter 16 Overview of the C++ Standard Library 671
Coding Principles 672
Use of Templates 673
Use of Operator Overloading 673
Overview of the C++ Standard Library 673
Strings 673
Regular Expressions 674
I/O Streams 674
Smart Pointers 674
Exceptions 675
Standard Integer Types 675
Numerics Library 675
Integer Comparisons 676
Bit Manipulation 676
Time and Date Utilities 677
Random Numbers 677
Initializer Lists 678
Pair and Tuple 678
Vocabulary Types 678
Function Objects 679
Filesystem 679
Multithreading 679
Type Traits 679
Standard Library Feature-Test Macros 679
< version>
Source Location 681
Stack Trace 681
Containers 681
Sequential Containers 682
Sequential Views 684
Container Adapters 684
Ordered Associative Containers 686
Unordered Associative Containers/Hash Tables 687
Flat Associative Container Adapters 687
bitset 688
Summary of Standard Library Containers 688
Algorithms 691
Non-modifying Sequence Algorithms 692
Modifying Sequence Algorithms 694
Operational Algorithms 695
Swap Algorithms 696
Partitioning Algorithms 696
Sorting Algorithms 697
Binary Search Algorithms 697
Set Algorithms on Sorted Sequences 697
Other Algorithms on Sorted Sequences 698
Heap Algorithms 698
Minimum/Maximum Algorithms 698
Numerical Processing Algorithms 699
Permutation Algorithms 700
Choosing an Algorithm 700
Ranges Library 701
What’s Missing from the Standard Library 702
Summary 702
Exercises 702
Chapter 17 Understanding Iterators and the Ranges Library 705
Iterators 706
Getting Iterators for Containers 708
Iterator Traits 710
Examples 711
Function Dispatching Using Iterator Traits 712
Stream Iterators 713
Output Stream Iterator: ostream_iterator 714
Input Stream Iterator: istream_iterator 715
Input Stream Iterator: istreambuf_iterator 715
Iterator Adapters 715
Insert Iterators 716
Reverse Iterators 717
Move Iterators 718
Ranges 720
Constrained Algorithms 721
Projection 722
Views 723
Modifying Elements Through a View 729
Mapping Elements 729
Range Factories 730
Input Streams as Views 731
Converting a Range into a Container 732
Summary 733
Exercises 733
Chapter 18 Standard Library Containers 735
Containers Overview 736
Requirements on Elements 737
Exceptions and Error Checking 739
Sequential Containers 739
vector 739
vector Overview 739
vector Details 742
Move Semantics 755
vector Example: A Round-Robin Class 756
The vector< bool>
deque 761
list 762
Accessing Elements 762
Iterators 763
Adding and Removing Elements 763
list Size 763
Special list Operations 763
list Example: Determining Enrollment 765
forward_list 766
array 769
Sequential Views 770
span 770
mdspan 772
Container Adapters 774
queue 774
queue Operations 774
queue Example: A Network Packet Buffer 775
priority_queue 777
priority_queue Operations 777
priority_queue Example: An Error Correlator 778
stack 779
stack Operations 780
stack Example: Revised Error Correlator 780
Associative Containers 780
Ordered Associative Containers 780
The pair Utility Class 781
map 781
multimap 790
set 794
multiset 796
Unordered Associative Containers Or Hash Tables 796
Hash Functions 796
unordered_map 798
unordered_multimap 802
unordered_set/unordered_multiset 803
Flat Set and Flat Map Associative Container Adapters 803
Performance of Associative Containers 804
Other Containers 804
Standard C-Style Arrays 804
Strings 805
Streams 806
bitset 806
bitset Basics 807
Bitwise Operators 807
bitset Example: Representing Cable Channels 808
Summary 811
Exercises 811
Chapter 19 Function Pointers, Function Objects, and Lambda Expressions 813
Function Pointers 814
findMatches() Using Function Pointers 814
findMatches() As a Function Template 816
Windows DLLs and Function Pointers 817
Pointers to Member Functions (And Data Members) 817
Function Objects 819
Writing Your First Function Object 819
Function Objects in the Standard Library 819
Arithmetic Function Objects 820
Comparison Function Objects 821
Logical Function Objects 823
Bitwise Function Objects 823
Adapter Function Objects 823
Polymorphic Function Wrappers 827
std::function 827
std::move_only_function 828
Lambda Expressions 829
Syntax 829
Lambda Expressions as Parameters 835
Generic Lambda Expressions 835
Lambda Capture Expressions 836
Templated Lambda Expressions 837
Lambda Expressions as Return Type 837
Lambda Expressions in Unevaluated Contexts 838
Default Construction, Copying, and Assigning 838
Recursive Lambda Expressions 839
Invokers 839
Summary 840
Exercises 840
Chapter 20 Mastering Standard Library Algorithms 843
Overview of Algorithms 844
The find and find_if Algorithms 845
The accumulate Algorithm 847
Move Semantics with Algorithms 848
Algorithm Callbacks 848
Algorithm Details 849
Non-modifying Sequence Algorithms 850
Search Algorithms 850
Specialized Searchers 851
Comparison Algorithms 852
Counting Algorithms 854
Modifying Sequence Algorithms 855
generate 856
transform 856
copy 857
move 858
replace 860
erase 860
remove 861
unique 862
shuffle 863
sample 863
reverse 864
Shifting Elements 864
Operational Algorithms 865
for_each 865
for_each_n 866
Partition Algorithms 866
Sorting Algorithms 867
Binary Search Algorithms 869
Set Algorithms 870
Minimum/Maximum Algorithms 872
Parallel Algorithms 874
Numerical Processing Algorithms 875
iota 876
Reduce Algorithms 876
Scan Algorithms 877
Constrained Algorithms 878
Constrained find 878
Constrained generate 878
Constrained for_each 879
Constrained-Only Algorithms 879
Summary 880
Exercises 880
Chapter 21 String Localization and Regular Expressions 883
Localization 884
Wide Characters 884
Non-Western Character Sets 885
Localizing String Literals 887
Locales and Facets 888
Locales 888
Global Locale 889
Using Locales 889
Character Classification 891
Character Conversion 891
Using Facets 891
Conversions 892
Regular Expressions 893
ECMAScript Syntax 894
Anchor 894
Wildcard 895
Alternation 895
Grouping 895
Quantifier 895
Precedence 896
Character Set Matches 896
Word Boundary 898
Back Reference 899
Lookahead 899
Regular Expressions and Raw String Literals 900
Common Regular Expressions 900
The regex Library 900
regex_match() 901
regex_match() Examples 902
regex_search() 904
regex_search() Examples 904
regex_iterator 905
regex_iterator Examples 905
regex_token_iterator 906
regex_token_iterator Examples 907
regex_replace() 909
regex_replace() Examples 909
Summary 911
Exercises 911
Chapter 22 Date and Time Utilities 913
Compile-Time Rational Numbers 914
Duration 916
Examples and Converting Durations 917
Predefined Durations 919
Standard Literals 920
hh_mm_ss 920
Clock 920
Printing Current Time 922
Execution Timing 922
Time Point 923
Date 925
Creating Dates 925
Printing Dates 927
Arithmetic with Dates 928
Time Zone 929
Summary 930
EXERCISES 930
Chapter 23 Random Number Facilities 931
C-Style Random Number Generation 932
Random Number Engines 933
Random Number Engine Adapters 934
Predefined Engines and Engine Adapters 935
Generating Random Numbers 936
Random Number Distributions 937
Summary 941
Exercises 941
Chapter 24 Additional Vocabulary Types 943
Variant 944
Any 946
Tuple 947
Decompose Tuples 949
Structured Bindings 949
tie 950
Concatenation 950
Comparisons 950
make_from_tuple 951
apply 952
Optional: Monadic Operations 952
Expected 953
Exceptions, Error Return Codes, and expected 956
Summary 956
Exercises 957
Part IV Mastering Advanced Features of C++ 959
Chapter 25 Customizing and Extending the Standard Library 961
Allocators 962
Extending the Standard Library 963
Why Extend the Standard Library? 964
Writing a Standard Library Algorithm 964
find_all 964
Modernized find_all 966
Writing a Standard Library Container 967
A Basic Directed Graph 967
Making directed_graph a Standard Library Container 977
Additional Standard Library–Like Functionality 991
Further Improvements 994
Other Container Types 994
Summary 994
Exercises 995
Chapter 26 Advanced Templates 997
More About Template Parameters 998
More About Template Type Parameters 998
Introducing Template Template Parameters 1001
More About Non-type Template Parameters 1003
Class Template Partial Specialization 1004
Emulating Function Partial Specialization with Overloading 1007
Template Recursion 1009
An N-Dimensional Grid: First Attempt 1009
A Real N-Dimensional Grid 1010
Variadic Templates 1012
Type-Safe Variable-Length Argument Lists 1013
constexpr if 1015
Variable Number of Mixin Classes 1015
Fold Expressions 1016
Metaprogramming 1018
Factorial at Compile Time 1019
Loop Unrolling 1020
Printing Tuples 1020
constexpr if 1022
Using a Compile-Time Integer Sequence with Folding 1023
Type Traits 1024
Using Type Categories 1025
Using Type Relationships 1027
Using the conditional Type Trait 1028
Using Type Modification Type Traits 1030
Using enable_if 1030
Using constexpr if to Simplify enable_if Constructs 1033
Logical Operator Traits 1034
Static Assertions 1034
Metaprogramming Conclusion 1035
Summary 1035
Exercises 1036
Chapter 27 Multithreaded Programming with C++ 1037
Introduction 1038
Race Conditions 1040
Tearing 1041
Deadlocks 1041
False Sharing 1043
Threads 1043
Thread with Function Pointer 1043
Thread with Function Object 1045
Thread with Lambda 1046
Thread with Member Function Pointer 1046
Thread-Local Storage 1047
Canceling Threads 1048
Automatically Joining Threads 1048
Cooperative Cancellation 1048
Retrieving Results from Threads 1050
Copying and Rethrowing Exceptions 1050
Atomic Operations Library 1053
Atomic Operations 1054
Atomic Smart Pointers 1056
Atomic References 1056
Using Atomic Types 1056
Waiting on Atomic Variables 1058
Mutual Exclusion 1059
Mutex Classes 1060
Spinlock 1060
Non-timed Mutex Classes 1061
Timed Mutex Classes 1062
Locks 1063
lock_guard 1063
unique_lock 1063
shared_lock 1064
Acquiring Multiple Locks at Once 1064
scoped_lock 1065
std::call_once 1066
Examples Using Mutexes 1067
Thread-Safe Writing to Streams 1067
Double-Checked Locking 1069
Condition Variables 1071
Spurious Wake-Ups 1072
Using Condition Variables 1072
Latches 1073
Barriers 1075
Semaphores 1076
Futures 1077
std::promise and std::future 1078
std::packaged_task 1079
std::async 1080
Exception Handling 1081
std::shared_future 1081
Example: Multithreaded Logger Class 1082
Thread Pools 1087
Coroutines 1088
Threading Design and Best Practices 1090
Summary 1091
Exercises 1092
Part V C++ Software Engineering 1093
Chapter 28 Maximizing Software Engineering Methods 1095
The Need for Process 1096
Software Life Cycle Models 1097
The Waterfall Model 1097
Benefits of the Waterfall Model 1098
Drawbacks of the Waterfall Model 1098
Sashimi Model 1099
Spiral-like Models 1099
Benefits of a Spiral-like Model 1100
Drawbacks of a Spiral-like Model 1101
Agile 1102
Software Engineering Methodologies 1102
Scrum 1102
Roles 1103
The Process 1103
Benefits of Scrum 1105
Drawbacks of Scrum 1105
The Unified Process 1105
The Rational Unified Process 1106
RUP as a Product 1107
RUP as a Process 1107
RUP in Practice 1107
Extreme Programming 1108
XP in Theory 1108
XP in Practice 1112
Software Triage 1112
Building Your Own Process and Methodology 1113
Be Open to New Ideas 1113
Bring New Ideas to the Table 1113
Recognize What Works and What Doesn’t Work 1113
Don’t Be a Renegade 1113
Version Control 1114
Summary 1116
Exercises 1116
Chapter 29 Writing Efficient C++ 1117
Overview of Performance and Efficiency 1118
Two Approaches to Efficiency 1118
Two Kinds of Programs 1118
Is C++ an Inefficient Language? 1118
Language-Level Efficiency 1119
Handle Objects Efficiently 1120
Pass-by-Value or Pass-by-Reference 1120
Return-by-Value or Return-by-Reference 1122
Catch Exceptions by Reference 1122
Use Move Semantics 1122
Avoid Creating Temporary Objects 1122
Pre-allocate Memory 1123
Use Inline Functions 1123
Mark Unreachable Code 1124
Design-Level Efficiency 1125
Cache Where Necessary 1125
Use Object Pools 1126
An Object Pool Implementation 1126
Using the Object Pool 1130
Profiling 1131
Profiling Example with gprof 1132
First Design Attempt 1132
Profiling the First Design Attempt 1135
Second Design Attempt 1137
Profiling the Second Design Attempt 1139
Profiling Example with Visual C++ 2022 1140
Summary 1142
Exercises 1142
Chapter 30 Becoming Adept at Testing 1145
Quality Control 1146
Whose Responsibility Is Testing? 1146
The Life Cycle of a Bug 1146
Bug-Tracking Tools 1147
Unit Testing 1149
Approaches to Unit Testing 1149
The Unit Testing Process 1150
Define the Granularity of Your Tests 1150
Brainstorm the Individual Tests 1152
Create Sample Data and Results 1153
Write the Tests 1153
Run the Tests 1154
Unit Testing in Action 1154
Introducing the Microsoft Visual C++ Testing Framework 1155
Writing the First Test 1157
Building and Running Tests 1157
Negative Tests 1158
Adding the Real Tests 1159
Debugging Tests 1161
Basking in the Glorious Light of Unit Test Results 1162
Fuzz Testing 1162
Higher-Level Testing 1162
Integration Tests 1162
Sample Integration Tests 1163
Integration Testing Techniques 1164
System Tests 1164
Regression Tests 1164
Tips For Successful Testing 1165
Summary 1166
Exercises 1166
Chapter 31 Conquering Debugging 1169
The Fundamental Law of Debugging 1170
Bug Taxonomies 1170
Avoid Bugs 1170
Plan For Bugs 1171
Error Logging 1171
Debug Traces 1173
Debug Mode 1174
Ring Buffers 1178
Assertions 1181
Crash Dumps 1183
Debugging Techniques 1183
Reproducing Bugs 1184
Debugging Reproducible Bugs 1185
Debugging Nonreproducible Bugs 1185
Debugging Regressions 1186
Debugging Memory Problems 1186
Categories of Memory Errors 1187
Tips for Debugging Memory Errors 1189
Debugging Multithreaded Programs 1191
Debugging Example: Article Citations 1192
Buggy Implementation of an ArticleCitations Class 1192
Testing the ArticleCitations Class 1195
Lessons from the ArticleCitations Example 1203
Summary 1204
Exercises 1204
Chapter 32 Incorporating Design Techniques and Frameworks 1207
“I Can Never Remember How To. . .” 1208
. . .Write a Class 1208
. . .Derive from an Existing Class 1210
. . .Write a Lambda Expression 1210
. . .Use the Copy-and-Swap Idiom 1211
. . .Throw and Catch Exceptions 1212
. . .Write a Class Template 1213
. . .Constrain Template Parameters 1214
. . .Write to a File 1214
. . .Read from a File 1214
There Must Be a Better Way 1215
Resource Acquisition Is Initialization 1215
Double Dispatch 1218
Attempt #1: Brute Force 1219
Attempt #2: Single Polymorphism with Overloading 1220
Attempt #3: Double Dispatch 1221
Mixin Classes 1223
Using Multiple Inheritance 1223
Using Class Templates 1225
Using CRTP 1226
Using CRTP and Deducing this 1227
Object-Oriented Frameworks 1227
Working with Frameworks 1228
The Model-View-Controller Paradigm 1228
Summary 1229
Exercises 1230
Chapter 33 Applying Design Patterns 1231
The Strategy Pattern 1232
Example: A Logging Mechanism 1232
Implementation of a Strategy-Based Logger 1233
Using the Strategy-Based Logger 1234
The Abstract Factory Pattern 1235
Example: A Car Factory Simulation 1235
Implementation of an Abstract Factory 1236
Using an Abstract Factory 1237
The Factory Method Pattern 1238
Example: A Second Car Factory Simulation 1238
Implementation of a Factory Method 1239
Using a Factory Method 1241
Other Uses 1242
Other Factory Patterns 1243
The Adapter Pattern 1244
Example: Adapting a Logger Class 1244
Implementation of an Adapter 1245
Using an Adapter 1246
The Proxy Pattern 1246
Example: Hiding Network Connectivity Issues 1246
Implementation of a Proxy 1247
Using a Proxy 1248
The Iterator Pattern 1248
The Observer Pattern 1249
Example: Exposing Events from Subjects 1249
Implementation of an Observable 1249
Using an Observer 1251
The Decorator Pattern 1252
Example: Defining Styles in Web Pages 1252
Implementation of a Decorator 1253
Using a Decorator 1254
The Chain of Responsibility Pattern 1254
Example: Event Handling 1255
Implementation of a Chain of Responsibility 1255
Using a Chain of Responsibility 1256
The Singleton Pattern 1257
Example: A Logging Mechanism 1258
Implementation of a Singleton 1258
Using a Singleton 1260
Summary 1261
Exercises 1261
Chapter 34 Developing Cross-Platform and Cross-Language Applications 1263
Cross-Platform Development 1264
Architecture Issues 1264
Size of Integers 1264
Binary Compatibility 1265
Address Sizes 1266
Byte Order 1266
Implementation Issues 1268
Compiler Quirks and Extensions 1268
Library Implementations 1268
Handling Different Implementations 1269
Platform-Specific Features 1269
Cross-Language Development 1271
Mixing C and C++ 1271
Shifting Paradigms 1271
Linking with C Code 1274
Calling C++ Code from C# 1276
Use C# Code from C++ and C++ from C# with C++/CLI 1278
Calling C++ Code from Java with JNI 1279
Calling Scripts from C++ Code 1281
Calling C++ Code from Scripts 1282
A Practical Example: Encrypting Passwords 1282
Calling Assembly Code from C++ 1284
Summary 1285
Exercises 1286
Part VI Appendices 1289
Appendix A C++ Interviews 1291
Chapter 1: A Crash Course in C++ and the Standard Library 1291
Things to Remember 1291
Types of Questions 1292
Chapters 2 and 21: Working with Strings and String Views, and String Localization and Regular Expressions 1293
Things to Remember 1293
Types of Questions 1294
Chapter 3: Coding with Style 1294
Things to Remember 1295
Types of Questions 1295
Chapter 4: Designing Professional C++ Programs 1295
Things to Remember 1296
Types of Questions 1296
Chapter 5: Designing with Classes 1297
Things to Remember 1297
Types of Questions 1297
Chapter 6: Designing for Reuse 1298
Things to Remember 1298
Types of Questions 1298
Chapter 7: Memory Management 1298
Things to Remember 1299
Types of Questions 1299
Chapters 8 and 9: Gaining Proficiency with Classes and Objects, and Mastering Classes and Objects 1299
Things to Remember 1300
Types of Questions 1301
Chapter 10: Discovering Inheritance Techniques 1302
Things to Remember 1303
Types of Questions 1303
Chapter 11: Modules, Header Files, and Miscellaneous Topics 1303
Things to Remember 1304
Types of Questions 1304
Chapters 12 and 26: Writing Generic Code with Templates, and Advanced Templates 1304
Things to Remember 1304
Types of Questions 1305
Chapter 13: Demystifying C++ I/O 1305
Things to Remember 1305
Types of Questions 1305
Chapter 14: Handling Errors 1305
Things to Remember 1306
Types of Questions 1306
Chapter 15: Overloading C++ Operators 1306
Things to Remember 1307
Types of Questions 1307
Chapters 16–20 and 25: The Standard Library 1307
Things to Remember 1307
Types of Questions 1308
Chapter 22: Date and Time Utilities 1308
Things to Remember 1309
Types of Questions 1309
Chapter 23: Random Number Facilities 1309
Things to Remember 1309
Types of Questions 1309
Chapter 24: Additional Vocabulary Types 1310
Things to Remember 1310
Types of Questions 1310
Chapter 27: Multithreaded Programming with C++ 1310
Things to Remember 1310
Types of Questions 1311
Chapter 28: Maximizing Software Engineering Methods 1311
Things to Remember 1311
Types of Questions 1312
Chapter 29: Writing Efficient C++ 1312
Things to Remember 1312
Types of Questions 1312
Chapter 30: Becoming Adept at Testing 1313
Things to Remember 1313
Types of Questions 1313
Chapter 31: Conquering Debugging 1313
Things to Remember 1313
Types of Questions 1314
Chapter 32: Incorporating Design Techniques and Frameworks 1314
Chapter 33: Applying Design Patterns 1314
Things to Remember 1314
Types of Questions 1314
Chapter 34: Developing Cross-Platform and Cross-Language Applications 1315
Things to Remember 1315
Types of Questions 1315
Appendix B Annotated Bibliography 1317
C++ 1317
Beginning C++ Without Previous Programming Experience 1317
Beginning C++ with Previous Programming Experience 1318
General C++ 1318
I/O Streams and Strings 1320
The C++ Standard Library 1320
C++ Templates 1321
C++11/C++14/C++17/C++20/C++23 1322
Unified Modeling Language 1322
Algorithms and Data Structures 1323
Random Numbers 1323
Open-Source Software 1323
Software Engineering Methodology 1324
Programming Style 1325
Computer Architecture 1326
Efficiency 1326
Testing 1327
Debugging 1327
Design Patterns 1327
Operating Systems 1328
Multithreaded Programming 1328
Appendix C Standard Library Header Files 1329
The C Standard Library 1329
Containers 1332
Algorithms, Iterators, Ranges, and Allocators 1332
General Utilities 1333
Mathematical Utilities 1335
Exceptions 1336
I/O streams 1336
Threading Support Library 1337
Appendix D Introduction to UML 1339
Diagram Types 1339
Class Diagrams 1340
Class Representation 1340
Relationship Representation 1340
Interaction Diagrams 1342
Sequence Diagrams 1342
Index 1345
EULA 1379

Erscheint lt. Verlag 8.1.2023
Reihe/Serie Tech Today
Sprache englisch
Themenwelt Informatik Programmiersprachen / -werkzeuge C / C++
Schlagworte C++ • Computer Science • Informatik • Programmierung / C u. C++ • Programmierung u. Software-Entwicklung • Programming & Software Development • Programming / C & C++
ISBN-10 1-394-19319-X / 139419319X
ISBN-13 978-1-394-19319-6 / 9781394193196
Haben Sie eine Frage zum Produkt?
PDFPDF (Adobe DRM)
Größe: 12,3 MB

Kopierschutz: Adobe-DRM
Adobe-DRM ist ein Kopierschutz, der das eBook vor Mißbrauch schützen soll. Dabei wird das eBook bereits beim Download auf Ihre persönliche Adobe-ID autorisiert. Lesen können Sie das eBook dann nur auf den Geräten, welche ebenfalls auf Ihre Adobe-ID registriert sind.
Details zum Adobe-DRM

Dateiformat: PDF (Portable Document Format)
Mit einem festen Seiten­layout eignet sich die PDF besonders für Fach­bücher mit Spalten, Tabellen und Abbild­ungen. Eine PDF kann auf fast allen Geräten ange­zeigt werden, ist aber für kleine Displays (Smart­phone, eReader) nur einge­schränkt geeignet.

Systemvoraussetzungen:
PC/Mac: Mit einem PC oder Mac können Sie dieses eBook lesen. Sie benötigen eine Adobe-ID und die Software Adobe Digital Editions (kostenlos). Von der Benutzung der OverDrive Media Console raten wir Ihnen ab. Erfahrungsgemäß treten hier gehäuft Probleme mit dem Adobe DRM auf.
eReader: Dieses eBook kann mit (fast) allen eBook-Readern gelesen werden. Mit dem amazon-Kindle ist es aber nicht kompatibel.
Smartphone/Tablet: Egal ob Apple oder Android, dieses eBook können Sie lesen. Sie benötigen eine Adobe-ID sowie eine kostenlose App.
Geräteliste und zusätzliche Hinweise

Zusätzliches Feature: Online Lesen
Dieses eBook können Sie zusätzlich zum Download auch online im Webbrowser lesen.

Buying eBooks from abroad
For tax law reasons we can sell eBooks just within Germany and Switzerland. Regrettably we cannot fulfill eBook-orders from other countries.

Mehr entdecken
aus dem Bereich
Das umfassende Handbuch

von Torsten T. Will

eBook Download (2024)
Rheinwerk Computing (Verlag)
CHF 48,75
C++ lernen - professionell anwenden - Lösungen nutzen

von Ulrich Breymann

eBook Download (2023)
Carl Hanser Fachbuchverlag
CHF 48,80
C++ lernen - professionell anwenden - Lösungen nutzen

von Ulrich Breymann

eBook Download (2023)
Carl Hanser Fachbuchverlag
CHF 48,80