Advanced C++

Book description

Become an expert at C++ by learning all the key C++ concepts and working through interesting exercises

Key Features

  • Explore C++ concepts through descriptive graphics and interactive exercises
  • Learn how to keep your development bug-free with testing and debugging
  • Discover various techniques to optimize your code

Book Description

C++ is one of the most widely used programming languages and is applied in a variety of domains, right from gaming to graphical user interface (GUI) programming and even operating systems. If you're looking to expand your career opportunities, mastering the advanced features of C++ is key.

The book begins with advanced C++ concepts by helping you decipher the sophisticated C++ type system and understand how various stages of compilation convert source code to object code. You'll then learn how to recognize the tools that need to be used in order to control the flow of execution, capture data, and pass data around. By creating small models, you'll even discover how to use advanced lambdas and captures and express common API design patterns in C++. As you cover later chapters, you'll explore ways to optimize your code by learning about memory alignment, cache access, and the time a program takes to run. The concluding chapter will help you to maximize performance by understanding modern CPU branch prediction and how to make your code cache-friendly.

By the end of this book, you'll have developed programming skills that will set you apart from other C++ programmers.

What you will learn

  • Delve into the anatomy and workflow of C++
  • Study the pros and cons of different approaches to coding in C++
  • Test, run, and debug your programs
  • Link object files as a dynamic library
  • Use templates, SFINAE, constexpr if expressions and variadic templates
  • Apply best practice to resource management

Who this book is for

If you have worked in C++ but want to learn how to make the most of this language, especially for large projects, this book is for you. A general understanding of programming and knowledge of using an editor to produce code files in project directories is a must. Some experience with strongly typed languages, such as C and C++, is also recommended.

Table of contents

  1. Preface
    1. About the Book
      1. About the Authors
      2. Learning Objectives
      3. Audience
      4. Approach
      5. Hardware Requirements
      6. Software Requirements
      7. Installation and Setup
      8. Installing the Code Bundle
      9. Additional Resources
  2. 1. Anatomy of Portable C++ Software
    1. Introduction
    2. Managing C++ Projects
      1. The Code-Build-Test-Run Loop
      2. Building a CMake Project
      3. Exercise 1: Using CMake to Generate Ninja Build Files
    3. Importing a CMake Project into Eclipse CDT
      1. Exercise 2: Importing the CMake File into Eclipse CDT
      2. Exercise 3: Adding New Source Files to CMake and Eclipse CDT
      3. Activity 1: Adding a New Source-Header File Pair to the Project
    4. Unit Testing
      1. Preparing for the Unit Tests
      2. Exercise 4: Preparing Our Project for Unit Testing
      3. Building, Running, and Writing Unit Tests
      4. Exercise 5: Building and Running Tests
      5. Exercise 6: Testing the Functionality of Code
      6. Activity 2: Adding a New Class and Its Test
    5. Understanding Compilation, Linking, and Object File Contents
      1. Compilation and Linking Steps
      2. Exercise 7: Identifying Build Steps
      3. The Linking Step
      4. Diving Deeper: Viewing Object Files
      5. Exercise 8: Exploring Compiled Code
    6. Debugging C++ Code
      1. Exercise 9: Debugging with Eclipse CDT
    7. Writing Readable Code
      1. Indentation and Formatting
      2. Use Meaningful Names as Identifiers
      3. Keeping Algorithms Clear and Simple
      4. Exercise 10: Making Code Readable
      5. Activity 3: Making Code More Readable
    8. Summary
  3. 2A. No Ducks Allowed – Types and Deduction
    1. Introduction
    2. C++ Types
      1. C++ Fundamental Types
      2. C++ Literals
    3. Specifying Types – Variables
      1. Exercise 1: Declaring Variables and Exploring Sizes
    4. Specifying Types – Functions
      1. Exercise 2: Declaring Functions
      2. Pointer Types
      3. Exercise 3: Declaring and Using Pointers
    5. Creating User Types
      1. Enumerations
      2. Exercise 4: Enumerations – Old and New School
      3. Structures and Classes
      4. Fraction Class
      5. Constructors, Initialization, and Destructors
      6. Class Special Member Functions
      7. Implicit Versus Explicit Constructors
      8. Class Special Member Functions – Compiler Generation Rules
      9. Defaulting and Deleting Special Member Functions
      10. Rule of Three/Five and Rule of Zero
      11. Constructors – Initializing the Object
      12. Exercise 5: Declaring and Initializing Fractions
      13. Values Versus References and Const
      14. Exercise 6: Declaring and Using Reference Types
      15. Implementing Standard Operators
      16. Implementing the Output Stream Operator (<<)
      17. Structuring Our Code
      18. Exercise 7: Adding Operators to the Fraction Class
      19. Function Overloading
      20. Classes, Structs, and Unions
      21. Activity 1: Graphics Processing
    6. Summary
  4. 2B. No Ducks Allowed – Templates and Deduction
    1. Introduction
    2. Inheritance, Polymorphism, and Interfaces
      1. Inheritance and Access Specifiers
      2. Abstract Classes and Interfaces
      3. Exercise 1: Implementing Game Characters with Polymorphism
      4. Classes, Structs, and Unions Revisited
    3. Visibility, Lifetime, and Access
      1. Namespaces
    4. Templates – Generic Programming
      1. What is Generic Programming?
      2. Introducing C++ Templates
      3. C++ Pre-Packaged Templates
    5. Type Aliases – typedef and using
      1. Exercise 2: Implementing Aliases
    6. Templates – More than Generic Programming
      1. Substitution Failure Is Not An Error – SFINAE
      2. Floating-Point Representations
      3. Constexpr if Expressions
      4. Non-Type Template Arguments
      5. Exercise 3: Implementing Stringify – specialization Versus constexpr
      6. Function Overloading Revisited
      7. Template Type Deduction
      8. Displaying the Deduced Types
      9. Template Type Deduction – the Details
      10. SFINAE Expression and Trailing Return Types
    7. Class Templates
      1. Exercise 4: Writing a Class Template
      2. Activity 1: Developing a Generic "contains" Template Function
    8. Summary
  5. 3. No Leaks Allowed - Exceptions and Resources
    1. Introduction
      1. Variable Scope and Lifetime
    2. Exceptions in C++
      1. The Need for Exceptions
      2. Stack Unwinding
      3. Exercise 1: Implementing exceptions in Fraction and Stack
      4. What Happens When an Exception is Thrown?
      5. Throw-by-Value or Throw-by-Pointer
      6. Standard Library Exceptions
      7. Catching Exceptions
      8. Exercise 2: Implementing Exception Handlers
      9. CMake Generator Expressions
      10. Exception Usage Guidelines
    3. Resource Management (in an Exceptional World)
      1. Resource Acquisition Is Initialization
      2. Exercise 3: Implementing RAII for Memory and File Handles
      3. Special Coding Techniques
      4. C++ doesn't Need finally
      5. RAII and the STL
      6. Who Owns This Object?
      7. Temporary Objects
      8. Move Semantics
      9. Implementing a Smart Pointer
      10. STL Smart Pointers
      11. std::unique_ptr
      12. std::shared_ptr
      13. std::weak_ptr
      14. Smart Pointers and Calling Functions
      15. Exercise 4: Implementing RAII with STL Smart Pointers
      16. Rule of Zero/Five – A Different Perspective
      17. Activity 1: Implementing Graphics Processing with RAII and Move
      18. When is a Function Called?
      19. Which Function to Call
      20. Identifiers
      21. Names
      22. Name lookup
      23. Argument-Dependent Lookup
      24. Caveat Emptor
      25. Exercise 5: Implementing Templates to Prevent ADL Issues
      26. Implicit Conversion
      27. Explicit – Preventing Implicit Conversion
      28. Contextual Conversion
      29. Exercise 6: Implicit and Explicit Conversions
      30. Activity 2: Implementing classes for Date Calculations
    4. Summary
  6. 4. Separation of Concerns - Software Architecture, Functions, and Variadic Templates
    1. Introduction
      1. The Pointer to Implementation (PIMPL) Idiom
      2. Logical and Physical Dependencies
      3. The Pointer to Implementation (PIMPL) Idiom
      4. Advantages and Disadvantages of PIMPL
      5. Implementing PIMPL with unique_ptr<>
      6. unique_ptr<> PIMPL Special Functions
      7. Exercise 1: Implementing a Kitchen with unique_ptr<>
    2. Function Objects and Lambda Expressions
      1. Function Pointers
      2. What is a Function Object?
      3. Exercise 2: Implementing function objects
      4. std::function<> template
      5. Exercise 3: Implementing callbacks with std::function
      6. What is a Lambda Expression?
      7. Capturing data into Lambdas
      8. Exercise 4: Implementing Lambdas
    3. Variadic Templates
      1. Activity 1: Implement a multicast event handler
    4. Summary
  7. 5. The Philosophers' Dinner – Threads and Concurrency
    1. Introduction
    2. Synchronous, Asynchronous, and Threaded Execution
      1. Concurrency
      2. Parallelism
      3. Synchronous Execution
      4. Asynchronous Execution
      5. Exercise 1: Creating Threads in a Different Way
    3. Review Synchronization, Data Hazards, and Race Conditions
      1. Exercise 2: Writing an Example of Race Conditions
      2. Data Hazards
      3. RAW Dependency
      4. WAR Dependency
      5. WAW Dependency
      6. Resource Synchronization
      7. Event Synchronization
      8. Deadlock
      9. Move Semantics for Multithreading Closures
      10. Exercise 3: Moving Objects to a Thread Function
      11. Exercise 4: Creating and Working with an STL Container of Threads
    4. Futures, Promises, and Async
      1. Exercise 5: Synchronization with Future Results
      2. Activity 1: Creating a Simulator to Model the Work of the Art Gallery
    5. Summary
  8. 6. Streams and I/O
    1. Introduction
      1. Reviewing the I/O Portion of the Standard Library
      2. Predefined Standard Stream Objects
      3. Exercise 1: Overriding the Left Shift Operator, <<, for User-Defined Types
      4. File I/O Implementation Classes
      5. Exercise 2: Reading and Writing User-Defined Data Types to a File
      6. String I/O Implementation
      7. Exercise 3: Creating a Function for Replacement Words in a String
      8. I/O Manipulators
      9. I/O Manipulators for Changing the Numeric Base of the Stream
      10. Exercise 4: Displaying Entered Numbers in Different Numeric Bases
      11. I/O Manipulators for Floating-Point Formatting
      12. Exercise 5: Displaying Entered Floating-Point Numbers with Different Formatting
      13. I/O Manipulators for Boolean Formatting
      14. I/O Manipulators for Field Width and Fill Control
      15. I/O Manipulators for Other Numeric Formatting
      16. I/O Manipulators for Whitespace Processing
      17. Making Additional Streams
      18. How to Make an Additional Stream – Composition
      19. Exercise 6: Composing the Standard Stream Object in the User-Defined Class
      20. How to Make an Additional Stream – Inheritance
      21. Exercise 7: Inheriting the Standard Stream Object
      22. Leveraging Asynchronous I/O
      23. Asynchronous I/O on Windows Platforms
      24. Asynchronous I/O on Linux Platforms
      25. Exercise 8: Asynchronously Reading from a File in Linux
      26. Asynchronous Cross-Platform I/O Libraries
      27. Interaction of Threads and I/O
      28. Exercise 9: Developing a Thread-Safe Wrapper for std::cout
      29. Using Macros
      30. Activity 1: The Logging System for The Art Gallery Simulator
    2. Summary
  9. 7. Everybody Falls, It's How You Get Back Up – Testing and Debugging
    1. Introduction
      1. Assertions
      2. Exercise 1: Writing and Testing Our First Assertion
      3. Static Assertions
      4. Exercise 2: Testing Static Assertions
      5. Understanding Exception Handling
      6. Exercise 3: Performing Exception Handling
    2. Unit Testing and Mock Testing
      1. Exercise 4: Creating Our First Unit Test Case
      2. Unit Testing Using Mock Objects
      3. Exercise 5: Creating Mock Objects
      4. Breakpoints, Watchpoints, and Data Visualization
      5. Working with the Stack Data Structure
      6. Activity 1: Checking the Accuracy of the Functions Using Test Cases and Understanding Test-Driven Development (TDD)
    3. Summary
  10. 8. Need for Speed – Performance and Optimization
    1. Introduction
    2. Performance Measurement
      1. Manual Estimation
      2. Studying Generated Assembly Code
      3. Manual Execution Timing
      4. Exercise 1: Timing a Program's Execution
      5. Timing Programs without Side Effects
      6. Source Code Instrumentation
      7. Exercise 2: Writing a Code Timer Class
    3. Runtime Profiling
      1. Exercise 3: Using perf to Profile Programs
    4. Optimization Strategies
      1. Compiler-Based Optimization
      2. Loop Unrolling
      3. Exercise 4: Using Loop Unrolling Optimizations
      4. Profile Guided Optimization
      5. Exercise 5: Using Profile Guided Optimization
      6. Parallelization
      7. Exercise 6: Using Compiler Parallelization
      8. Source Code Micro Optimizations
      9. Using the std::vector Container Efficiently
      10. Exercise 7: Optimizing Vector Growth
      11. Short-Circuit Logical Operators
      12. Exercise 8: Optimizing Logical Operators
      13. Branch Prediction
      14. Exercise 9: Optimization for Branch Prediction
    5. Further Optimizations
    6. Cache Friendly Code
      1. Exercise 10: Exploring the Effect of Caches on Data Structures
      2. Exercise 11: Measuring the Impact of Memory Access
      3. Caching
      4. Prefetching
      5. Effects of Caching on Algorithms
      6. Optimizing for Cache-Friendliness
      7. Exercise 12: Exploring the Cost of Heap Allocations
      8. Struct of Arrays Pattern
      9. Exercise 13: Using the Struct of Arrays Pattern
      10. Algorithmic Optimizations
      11. Exercise 14: Optimizing a Word Count Program
      12. Activity 1: Optimizing a Spell Check Algorithm
    7. Summary
  11. Appendix
    1. 1. Anatomy of Portable C++ Software
      1. Activity 1: Adding a New Source-Header File Pair to the Project
      2. Activity 2: Adding a New Class and Its Test
      3. Activity 3: Making Code More Readable
    2. 2A. No Ducks Allowed – Types and Deduction
      1. Activity 1: Graphics Processing
    3. 2B. No Ducks Allowed – Templates and Deduction
      1. Activity 1: Developing a Generic "contains" Template Function
    4. 3. The Distance between Can and Should – Objects, Pointers and Inheritance
      1. Activity 1: Implementing Graphics Processing with RAII and Move
    5. Activity 2: Implementing classes for Date Calculations
    6. 4. Separation of Concerns - Software Architecture, Functions, Variadic Templates
      1. Activity 1: Implement a multicast event handler
    7. 5. The Philosophers' Dinner – Threads and Concurrency
      1. Activity 1: Creating a Simulator to Model the Work of the Art Gallery
    8. 6. Streams and I/O
      1. Activity 1 The Logging System for The Art Gallery Simulator
    9. 7. Everybody Falls, It's How You Get Back Up – Testing and Debugging
      1. Activity 1: Checking the Accuracy of the Functions Using Test Cases and Understanding Test-Driven Development (TDD)
    10. 8. Need for Speed – Performance and Optimization
      1. Activity 1: Optimizing a Spell Check Algorithm

Product information

  • Title: Advanced C++
  • Author(s): Gazihan Alankus, Olena Lizina, Rakesh Mane, Vivek Nagarajan, Brian Price
  • Release date: October 2019
  • Publisher(s): Packt Publishing
  • ISBN: 9781838821135