Table Of ContentModern C++ For Software Developers
Serious C++ Development
Karan Singh Garewal
Modern C++ For Software Developers
Karan Singh Garewal
Copyright © 2022+, Karan Singh Garewal
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of
the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations,
recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or
information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar
methodology now known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol
with every occurrence of a trademarked name, logo, or image we use the names, logos, and images
only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement
of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they
are not identified as such, is not to be taken as an expression of opinion as to whether or not they are
subject to proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of
publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for
any errors or omissions that may be made. The publisher makes no warranty, express or implied, with
respect to the material contained herein.
Cover Image Design by Kirill Tonkikh, unsplash.com
I
Changelog
Date Version Notes
October 10, 2022 1.3 new chapter on coroutines
additions to the GDB Debugger chapter
August 30, 2022 1.2 std::format library function
Revise threads chapter with additional working
examples.
Numerous edits to improve readability and improve
comprehension.
July 30, 2022 1.1 setjmp and longjmp section
refactor smart pointers chapter
C++ Sanitizers chapter
fix errors in some code examples
[[maybe_unused]] – C++17 features
C++ SonarLint chapter
various edits to explain concepts more simply
February 28, 2022 1.0 Initial release
II
Preface
This is a book on serious software development with Modern C++. It is
my go-to desktop reference when I am developing C++ applications. I
hope that you will also consider this book in such an exalted light.
This book is divided into eight main sections. The first section is a C
language refresher. Knowledge of the C language is presumed. The
next section exposes core C++. This is C++ before C++11. This
section is followed by four sections that discuss important features of
C++11, C++14, C++17 and the latest standard, C++20. This is
followed by a section that discusses important functions in the C++
Standard Library. The next section is devoted to the GNU C++
compiler and the GNU debugger. The last section looks at some
miscellaneous topics.
Every important C++ feature that is discussed in this book is
accompanied by a short C++ program to demonstrate how the feature
works. You can cut and paste these examples into wandbox
(https://wandbox.org) and then compile and execute them.
This book can be read sequentially or you can go directly to topics of
interest.
The reminder of this preface is merely my opinionated meandering on
C++ web applications. Is C++ web application development an
anachronism? You can safely omit this part of the preface.
III
A Journey Through C++ Land
When I was going to university, I had a friend who was fond of saying
“I think in C”. He obviously liked C a lot. Over forty years later, after
it’s inception, C still remains very popular. A lot of people really like C.
It appears that C imposes very little cognitive load on the brain; C fits
easily into the brain.
But C has it’s limitations. A few years back I was developing a deep
neural network in C. After writing about 30,000 lines I started having
difficulty reasoning about the application in it’s entirety. This is not a
critique about the language, it is an observation that C does not
provide language constructs to architect large applications.
This is where C++ comes in. C++ provides constructs to structure and
architect extremely large applications. Applications in the multi-million
line range are eminently feasible. This is entirely due to constructs
such as classes, encapsulation, function overloading, run-time
polymorphism and templates. These constructs are remarkably
versatile and a very large domain of problems can be modelled with
these constructs.
But this not to say that C++ is perfect. It is possible that absolutely
massive software applications such as the F-35 fighter jet program (up
to 30 million C++ Source lines of code) are exposing the deficiencies
in C++. In other words, C++ source code is not reliable enough at this
scale. The C++ Steering Committee is aware of this issue. Each new
release of C++ brings new constructs to improve the correctness of
IV
C++ programs. Consider for example, const, static_assert, constexpr,
consteval, constinit, typed enums, constant templates, auto, type
deduction, braced initialization, noexcept, override, [[nodiscard]] and
a plethora of other language constructs.. The list of C++ correctness
constructs is long and expanding.
C++ Is Not A Web Programming Language
This is a frequently repeated canard on the Internet. It may have been
true in the past but it is not true today. Web frameworks based on
dynamically typed languages are invariably held forth as being the
best environments to develop web applications. I am alluding to the
Python/Django and Ruby/Rails frameworks in particular. I came from a
heavy C++ background and migrated to web development. I spent
nearly a decade developing Rails applications. Never liked the
language or the framework. But it would have been an unforgivable
heresy to oppose conventional wisdom.
Frameworks based on dynamically typed languages are held out as
being suitable for fast web development. I disagree. An experienced
C++ programmer can develop web applications just as fast as
someone developing in the Ruby and Rails environment for example. If
not faster. How can web development in C++ be faster? It all boils
down to the compile-link cycle in C++. If your C++ web application
compiles and links properly it is almost certain that it will also run on
the web. Your main concern will be the “business” logic of your
program. In contrast, if the application is developed in a dynamically
typed language, you can write the application quickly but you will
V
spend a lot of time debugging the program at run-time. This is due to
the fact that in a dynamically typed language variable types
frequently change at run-time. Additionally the debugging tools for
dynamically typed languages are mediocre.
In the discussion that follows I will use Ruby and Rails as a bete noire.
Simply because this is the framework with which I have the most
experience and this framework has a huge hype machine behind it.
However the discussion applies equally to other frameworks built with
dynamically typed languages.
Performance
There is a dirty little secret concerning web applications built with
dynamically typed languages. These applications are very slow and a
lot of engineering effort goes into making them run faster. For
example, a C++ web application developed in the Drogon framework:
( https://github.com/drogonframework/drogon ) is over fifty times
faster than a Ruby/Rails application.
See: https://www.techempower.com/benchmarks/#section=data-
r19&hw=ph&test=composite
The main culprit is the interpreter in these languages which must read
each source code statement (or it’s bytecode) before executing the
statement.
Also see a comparison of the Drogon webserver with the gold standard
in webservers: Nginx.
https://drogon.docsforge.com/master/benchmarks/#test-plan-and-
VI
results
It is worth-noting that a medium-sized C++ web application will hardly
register any CPU usage. An equivalent Ruby/Rails application will
stress the CPU and you might end up having to load balance incoming
HTTP requests to multiple machines.
Libraries vs. Frameworks
Using a web framework leads the developer into vendor lock-in. If you
develop a web application in Python and Django or Ruby and Rails,
your application will for all practical purposes be locked into the
vendor’s framework. Migration to another framework will be a major
undertaking.
Libraries do not produce such a lock-in effect. After all, you can easily
switch libraries or develop your own library functions. For example.
Drogon is a very thin framework layer wrapped around the drogon
webserver.
Deployment
Deploying Ruby and Rails applications to production servers is
complicated. All of the source files and static resources have to be
deployed on the production server. In contrast the deployment of a C+
+ web application is simple. One or more executable files and the
static resources are deployed on the production server. rsync can
easily manage this deployment.
VII
Trying The Theory Out
I wanted to confirm my suspicions with a production quality C++ web
application. Since I am an Attorney at Law, I developed
https://truelawdocs.com as a Drogon C++ application. This is a multi-
threaded application for document production. It took about four
months of part-time work. The application uses the Cassandra NoSQL
database for document storage. This is clearly massive overkill for an
application like TrueLawDocs. Cassandra slowed the development
cycle since I had zero prior Cassandra experience. I wanted to learn
Cassandra on the supposition that I might need this column-oriented
NoSQL database in the future. I really liked Cassandra, it’s very well
designed.
TrueLawDocs has a front-end developed in Bootstrap, Vue, Javascript
and CSS. The C++ back-end and the front-end communicate through
websockets. As you can surmise TrueLawDocs has a strongly
decoupled architecture.
Aside from the Drogon framework and the C++ standard library, the
only libraries used were nlohmann/json a C++ JSON library, AES.hpp a
header only C++ encryption library, the DataStax C driver library for
Cassandra, ASAN (address sanitizer) and UBSAN (undefined behaviour
sanitizer). That is it for third party libraries. Everything else was hand-
coded.
For payment integration with Stripe, the LibCurl library was used to
interact with the Stripe payment server. Stripe does not support C++
and provides no sample code to integrate C++ applications. The
integration of the TrueLawDocs C++ code with the Stripe server
VIII
exemplifies the raw power of C++.
The overall development experience was very pleasant. The Drogon
source code is easy to digest; it’s written by a master of Modern C++.
TrueLawDocs including Cassandra is running on a seven dollar a
month VPS rented from a company In Sharjah.
Lessons Learned
During my tenure contracting on Rails applications I rarely met
developers who had broad experience with other programming
languages. They typically only knew their framework. In a decade of
contracting, I never met a Rails programmer who was reasonably
proficient in C++.
One of the reasons that dynamically typed web languages are popular
is that they are easy to learn. You can master Rails in less than three
months. In contrast one cannot gain reasonable proficiency in C++
unless one has programmed in the language for about two years. The
Modern C++ learning curve is very steep. Unfortunately. It’s
unavoidable.
Another factor is economics. Web applications built in dynamically
typed languages rely on cheap labour. Fortune 500 companies use
large inputs of foreign contractors and software quality testers to
develop and maintain their applications. To my mind, this is a
statement on the inadequacy of dynamically typed languages for web
development. If these cheap resources were not available, the
development model would shift to conserving expensive, high quality
IX