Book Image

Advanced C++ Programming Cookbook

By : Dr. Rian Quinn
Book Image

Advanced C++ Programming Cookbook

By: Dr. Rian Quinn

Overview of this book

If you think you've mastered C++ and know everything it takes to write robust applications, you'll be in for a surprise. With this book, you'll gain comprehensive insights into C++, covering exclusive tips and interesting techniques to enhance your app development process. You'll kick off with the basic principles of library design and development, which will help you understand how to write reusable and maintainable code. You'll then discover the importance of exception safety, and how you can avoid unexpected errors or bugs in your code. The book will take you through the modern elements of C++, such as move semantics, type deductions, and coroutines. As you advance, you'll delve into template programming - the standard tool for most library developers looking to achieve high code reusability. You'll explore the STL and learn how to avoid common pitfalls while implementing templates. Later, you'll learn about the problems of multithreaded programming such as data races, deadlocks, and thread starvation. You'll also learn high-performance programming by using benchmarking tools and libraries. Finally, you'll discover advanced techniques for debugging and testing to ensure code reliability. By the end of this book, you'll have become an expert at C++ programming and will have gained the skills to solve complex development problems with ease.
Table of Contents (15 chapters)

Using atomic data types

In this recipe, we will learn how to use atomic data types in C++. Atomic data types provide the ability to read and write simple data types (that is, a Boolean or integer) without the need for thread synchronization (that is, the use of std::mutex and friends). To accomplish this, atomic data types are implemented using special CPU instructions that ensure when an operation is executed, it is done so as a single, atomic operation.

For example, incrementing an integer can be written as follows:

int i = 0;

auto tmp = i;
i = tmp; // i == 1

An atomic data type ensures that this increment is executed such that no other attempts to increment the integer simultaneously can interleave, and therefore result in corruption. How this is done by the CPU is out of the scope of this book. That's because this is extremely complicated in modern, super-scalar,...