C++ High Performance Second Edition Master the art of optimizing the functioning of your C++ code Björn Andrist Viktor Sehr BIRMINGHAM - MUMBAI C++ High Performance Second Edition Copyright © 2020 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. Producer: Tushar Gupta Acquisition Editor – Peer Reviews: Divya Mudaliar Content Development Editor: Joanne Lovell Technical Editor: Gaurav Gavas Project Editor: Mrunal Dave Proofreader: Safis Editing Indexer: Priyanka Dhadke Presentation Designer: Sandip Tadge First published: January 2018 Second Edition: December 2020 Production reference: 1181220 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-83921-654-1 www.packt.com packt.com Subscribe to our online digital library for full access to over 7,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website. Why subscribe? Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals Learn better with Skill Plans built especially for you Get a free eBook or video every month Fully searchable for easy access to vital information Copy and paste, print, and bookmark content Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.Packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details. At www.Packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks. Foreword Two years ago, the first edition of C++ High Performance was published, and I had the privilege of writing its foreword. Then, C++17 was state of the art and C++20 was in the early stages of development. Now, C++20 is widely available for development and specification work on C++23 is underway. C++ stepped onto the stage in 1983, and hasn't stopped reinventing itself for a single year since. It has gone from a single frontend language on top of C to a first-class citizen of the compiler world. The continued wide use, as it nears its 40th anniversary, is a testament to both its incredible depth and diverse features. Each new C++ standard has added substantial functionality —sometimes to excess. In the words of Stroustrup, "Within C++, there is a much smaller and cleaner language struggling to get out." The problem, of course, is that the "smaller and cleaner language" to be found within C++ changes with each and every situation. Mastering C++ is akin to mastering a multitude of domain-specific languages, each tailored to a specific use. The dialect that makes sense for an embedded system is nonsensical for large enterprise applications, and the phrasing that powers a game engine is unbearable when applied to a word processor. C++ High Performance teaches you a C++ dialect for rapidly developing high-performance code. From C++11 onward, there has been a vast array of new features in both the C++ language and the C++ STL. When applied with care, they let you spend more time writing your application and less time handling implementation details. This is the focus of the book and where it shines. One of the biggest topics that separates professionals from journeymen in C++ is understanding, from top to bottom, what is really happening in their code. Ultimately, a programmer is responsible for driving hardware in service of their goals, and the concepts in this book will help you develop an intuitive understanding of what your code is doing under the hood. Each topic is framed in the larger context of application development and computer science. For the reader who needs to get up to speed with the latest C++ techniques on short notice, this information provides the necessary landmarks for you to stay oriented. Specific examples, recipes, and logical progressions take you from a basic use of auto and <algorithm> all the way up to using asynchronous coroutines and parallel algorithms. Fundamental issues around modern C++, such as memory management and ownership, considerations of time and space, advanced template usage and others, are explained step by step; by the later chapters, the reader can proceed into advanced territory with confidence. Since the first edition, every topic has been revisited and expanded to be up to date with the latest standards. I have worked on a wide variety of projects—large and small, low level and managed, and some even in custom languages I designed and built—but C++ holds a special place in my heart. My first full-time job was writing C++ code for a game technology company in the early 2000s. I loved it, not least of all because a big part of the technology revolved around the reflection of the C++ code base into the editor and scripting language. Someone once described C++ as an octopus made by nailing extra legs onto a dog, and I spent a lot of time with a hammer making our code base do things that C++ was never intended to do. Yet the octopus we ended up with was, in its own way, beautiful and very effective. C++ has evolved tremendously since those days, and it is my privilege to open the door for you as you walk into an exciting new world of possibilities. Viktor and Björn are brilliant and experienced developers with a remarkable pedigree, and they have a lot of great things in store for you. Ben Garney CEO, The Engine Company Contributors About the authors Björn Andrist is a freelance software consultant currently focusing on audio applications. For more than 15 years, he has been working professionally with C++ in projects ranging from UNIX server applications to real-time audio applications on desktop and mobile. In the past, he has also taught courses on algorithms and data structures, concurrent programming, and programming methodologies. Björn holds a BS in computer engineering and an MS in computer science from KTH Royal Institute of Technology. I'm overwhelmed by the positive responses the first edition of this book has generated. The feedback has been a true source of inspiration and the major reason for me taking the time to write a second edition. Thank you to all readers and reviewers!Without the team at Packt Publishing you wouldn't have this book in your hands. Writing a book for the Expert Insight series has been a true pleasure. Special thanks goes to Joanne Lovell, Gaurav Gavas, and Tushar Gupta. The technical reviewers of this book have been extraordinary. Timur Doumler, the main technical reviewer, has been nothing but outstanding throughout the project. Thank you so much! Thank you Lewis Baker, Arthur O'Dwyer, and Marius Bancila also.Last, and most of all, I must thank my family for their support and their patience, again. Thank you Aleida, Agnes, and Clarence. Viktor Sehr is the founder and main developer of the small game studio Toppluva AB. At Toppluva, he develops a custom graphics engine that powers the open-world skiing game Grand Mountain Adventure. He has 13 years of professional experience using C++, with real-time graphics, audio, and architectural design as his focus areas. Across his career, he has developed medical visualization software at Mentice and Raysearch Laboratories, as well as real-time audio applications at Propellerhead Software. Viktor holds an MS in media science from Linköping University.