Articles on C++
Last updated: 2023/02/28
Top deep-dives on C++
The Last Vestiges Of Object Oriented Programming
One of the design approaches I'm not too experienced with is OOP. I've heard it's got its good sides, and its bad sides, but have had few concrete examples of either. In this informative article, Geoffrey Viola uses C++ to demonstrate some of the limitations of OOP, and how they can be re-implemented better using simpler constructs than classes. Regardless of OOP experience, I think this is a good one for you because of its applicable examples.
You ever crack into a new codebase and feel your head gradually begin to ache? I call that headache code, and try my best to avoid writing it at all costs. How? By following certain patterns when it comes to project structure and code design. In this concise article, Marius Elvert demonstrates with an example in C++, one of the concepts I try to implement in my own coding; prioritizing code breadth over depth by creating consecutive functions with returns, over embedded ones.
The best engineering interview question I’ve ever gotten, Part 1
Arthur O'Dwyer covers a great interview question he had. The first part just introduces the question, the second part is where the implementation is actually at. The question is about implementing multiply in memcached.
ARM and Lock-Free Programming
A common issue in programming is the formation of data races in asynchronous code. This often comes up when you're sharing data between threads. One approach in solving these issues is akin to Japanese carpentry without nails; lock-free concurrency programming. In this instructive article, Bruce Dawson introduces an example problem with cross thread data access, underlines some of the issues it could lead to, explains why a potential solution isn't in fact a solution, and finally offers a more reliable alternative, all in C++.
Why it is important to apply static analysis for open libraries that you add to your project
"Modern applications are built from third-party libraries like a wall from bricks", and although you might not be an expert builder, I'm sure that you can image that not all bricks are equal. And neither are third-party libraries. In this article, Andrey Karpov presents a couple of errors he caught in third-party libraries using a static analyzer. Although it's kind of a sales pitch, the topics he covers are important and applicable to any developer.
Inheritance Without Pointers
"Inheritance is a useful but controversial technique in C++". Basically it's easy to use incorrectly, but it's fairly useful in certain circumstances. Everything in moderation, right? Jonathan Boccara's article takes a look at a technique byPavel Novikov for using inheritance in C++ without pesky pointers to complicate implementation.
C++ and passing by value
More often than not, if you're working in C++, you're looking to optimize performance. Although premature optimization is a bad thing, ingraining optimal patterns into your everyday programming can save you time down the line. Matt Godbolt has written an aritcle presenting how passing by value in C++ functions where you intend to copy the argument is less expensive than the alternatives.
More and More Utilities in C++20
With great updates, come great responsibilities in finding out what new features those updates hold. That's the saying right? Well Rainer Grimm has got you covered for C++20, as always. In this article, Rainer explroes the new utility functions offered in C++20, including midpoint and linear interpolation, creating arrays, checking if a string starts or ends with a substring, and std::bind_front.
A General Overview of What Happens Before main()
Phillip Johnston explores what happens before main() in C++ and C programs. The article was originally published in 2019, but was updated again just yesterday.
Contracts, Preconditions & Invariants
Someone once told me that code is for people, not computers. You might not agree with it, but it makes a lot sense to me, and falls under the same umbrella as a similar saying, hardware is cheap, developers are expensive. Andrzej's article defines contracts as all of the information a user needs to use a component correctly, then goes on to exploring methods for guaranteeing the proper use of code with preconditions and invariants.
Frequency Domain Image Compression and Filtering
I'll be upfront and say this one isn't coding heavy, although it does have C++ code to go along with it. As many of you know, I have a background in electrical engineering, and signal processing is one of the most fascinating aspects of that. In this informative article, Alan Wolfe illuminates how it's done, and the results of processing in the frequency domain. Alan covers image compression, filtering, and convolution, all with accompanying images.
Writing a custom iterator in modern C++
Iterators are those lovely things that act as the backboone for many wonderful programming tools (mapping, data structure navigation, etc). But how do you go about implementing your own? Although this article is a bit of a tutorial, the author does an excellent job of explaining the design choices and individual steps in the process.
Reflection for aggregates
"An aggregate is an array or a class with
std::exchange Patterns: Fast, Safe, Expressive, and Probably Underused
If you're unfamiliar with std::exchange, it basically just takes an object value, replaces it with a new value, and then returns the old object value. Does that sound familiar? Well if it doesn't, Ben Deane's article does an excellent job of giving some good example use cases for exchange, including iterators and passing variables in a multi-thread environment. Ben also compares it to swap and move.
"Clean" Code, Horrible Performance
Casey Muratori discusses the idea of "clean code" and how it can affect the performance of a program.
- Casey argues that "clean" code is not very performant
- Uses an example to demonstrate his point
- I feel like it's pretty obvious that there's often a tradeoff between performance and "clean" code, but still an interesting perspective to read about
Code memory safety and efficiency by example
Memory leaks lead to a death by a thousand cuts for a program. The topic also always brings me back my first C++ course in college (shudder). But it's about time we stop letting amazing hardware make up for our poor programming! In this extensive article, Marty Kalin gives an overview of memory for executing C programs, nested heap allocation, memory leakage and heap fragmentation, and static area storage.
C++20 modules with GCC11
C++20 brings with it many new features, THAT MIGHT ALTER THE COURSE OF HISTORY! One such feature is the new module system, that "possibly signal headers’ ultimate demise". At least according to Niall Cooling. Having found resources elsewhere lacking, Niall took it upon himself to write an informative article on C++20 modules, where he explains why modules are being introduced, how "there is no one way of correctly using C++20 modules", and some obligatory breakdowns of different examples of modules' features.
C++ coroutines: The mental model for coroutine promises
Async/awaits are great, because they allow for asynchronous code execution, which means less time spent just standing around twiddling our thumbs. How is async code actually implemented underhood though? In this article, because everybody loves him, Raymond Chen depicts how C++ achieves async operation with co-routines and state. Raymond primarily lays the over-arching groundwork for the next article that focuses on implementation.
C++ exceptions under the hood
Exceptional debugging information can make a mediocre programmer exceptional. That is, if they have learned the suprisingly uncommon art of reading error codes (seriously, how is this that uncommon?). Well a big part of exceptional debugging information is the exception system! But how exactly do you build a system for handling unexpectedness? Nico Brailovsky's article covers setting up a system from scratch in C++ for throwing and catching exceptions.
Rapidly Solving Sudoku, N-Queens, Pentomino Placement, and More, With Knuth’s Algorithm X and Dancing Links.
Knuth's Algorithm X is a method for solving exact cover problems. Alan Wolfe dives into the algorithm with some examples to figure out how it works in action.
- The goal of an exact cover problem is to find a set of options which cover all items exactly once
- All NP problems can be reduced to cover problems
- Dancing links (DLX) is a technique for adding and deleting a node from a circular doubly linked list
Semantic requirements in concepts
Generic programming (GP) is a style of computer programming in which algorithms are written in terms of types to-be-specified-later that are then instantiated when needed for specific types provided as parameters. In GP, a concept is a description of supported operations on a type, including syntax and semantics. Andrzej Krzemieński (try to say that name right the first time) has written an article that focuses on concepts in C++, a somewhat related but not truly one-to-one feature, and how an inexpressible part of the feature might occasionally break it.
Changing std::sort at Google’s Scale and Beyond
Danila Kutenin illuminates the history of sort in C++, discusses a few issues with the current implementation, and presents a new solution.
Moves in Returns
Working in C++, you have to be acutely aware of when you're passing around values or references, or copying/moving data. In this example-filled article, Philip Trettner dissects a number of "return-by-value" code snippets, illuminating when exactly a copy, move, or elide takes place.
std::span in C++20: Bounds-Safe Views for Sequences of Objects
The implementation of more abstracted ideas in lower-level languages can be controversial. You get a nice shortcut for doing things, but you lose the detail in the abstraction. One of such features, is the new span object in C++20. Well if you want to use it, Rainer Grimm's article, like always, does an excellent job of describing how to use span for continuous sequences with the help of plenty of examples in C++.
How X Window Managers Work, And How To Write One (Part I)
If you're familiar with Linux, you're definitely familiar with X window managers. Do you know how the windowing system on your machine works though? Chuan Ji has written a three part series on the subject (title kind of gives it away). Although this series of articles is from 2014, the concepts of the first article still hold up. The implementations in the second article might have some updates, but overall it's still quality content on an essential part of your bread maker (in this case I mean your computer, the thing that earns you money, however it could be an essential part of your actual bread maker!).
Little C++ Standard Library Utility: std::align
Learning about obscure features in a language can save you a lot of time when you stumble across a problem that it was built for. Lesley Lai's article introduces the std::align feature in C++ and explores its functionality by implementing an arena allocator as an example of its use.
Things to keep in mind when working with POSIX signals
Kirill Ovchinnikov brings to light a number of common issues that arise when working with POSIX signals.
malloc() and free() are a bad API
The article discusses the shortcomings of the C memory allocation functions malloc() and free(), and how they could be improved. The main problems are that they don't allow for specifying custom alignment, don't store metadata about the allocated memory, and can waste space. Jonathan Müller proposes a new interface that would solve these problems.
- C++17 and C++23 have made some improvements to operator new and std::allocator to address some of the problems with the C allocation functions, but there are still some shortcomings
- Rust doesn't have these problems (lol)
How To Build an Evil Compiler
Akila Welihinda implements a compiler backdoor (Thompson attack ) using C++.
Borrowing Trouble: The Difficulties Of A C++ Borrow-Checker
Rust has a borrow checker. What does it do? Basically enforces certain rules, like that all variables are initialized before they are used, that you can't move the same value twice, that you can't move a value while it is borrowed, that you can't access a place while it is mutably borrowed (except through the reference), that you can't mutate a place while it is immutably borrowed, and more. The authors of this article (emails listed at top of article) detail an implementation of a borrow checker system at compile time in C++.
An Efficient Data Structure for 3D Multi-Layer Terrain and Erosion Simulation
Nick McDonald demonstrates how the Layer Map data structure is effective for simulating geo-morphology.
C++ Coroutines Do Not Spark Joy
Coroutines have been defined in the C++ standard as "simply a function that behaves differently when called multiple times: Instead of restarting from the start on each call, it will continue running after the return statement that last returned". In this informative article, Malte Skarupke explains why the current coroutine implementation in C++ doesn't really fit the language design, and goes on to manually implement them to give you a better idea of how they work.
C++20 Coroutine Iterators
A coroutine is a function that can suspend execution to be resumed later. This makes them especially useful for generator style functions or infinite lazy-computed sequences. This article by Martin Bond implements an "iterator to the [previously defined] template to support the range-for loop and iterative algorithms". Martin also makes a note of features/quirks from previous versions of C++.
saturating_add vs. saturating_int – new function vs. new type?
Jonathan Müller discusses the different approaches of "implementing integer arithmetic that saturates instead of overflowing" in C++.
Assignment for optional<T>
Barry Revzin dives in deep into copy assignment for optional
Porting 58000 lines of D and C++ to jai, Part 0: Why and How
In this series of blog posts, Simon van Bernem will document his experience of porting a game from D and C++ to the jai programming language. This is only the first part of the series and other parts aren't out yet, but it'll be an interesting series to follow.
- The game is 58,620 lines of code
- Simon isn't satisfied with the C++ ecosystem and where the language is going
- Simon does not recommend using D for serious projects on Windows, primarily because debug info is broken
T* makes for a poor optional<T&>
In this informative article, Barry Revzin explains the nuances of why T* and why have the optional meta function would make it easier for programmers to write algorithms.
Coercing deep const-ness
Const-ness is considered useful because you can mentally check off a variable as being immutable. In this article, Barry Revzin first shows us how C++ "function template that both enforces and coerces that it does not mutate its argument" that only works with pointers and references. Barry then goes on to implement a function template of a similar nature that works with spans.
Non-standard containers in C++
Evgeny Shulgin does a deep-dive on a number of the containers in C++, including array, vector, fbvector, deque, forward_list, list, and more obscure ones. There are also useful graphics to help conceptualize the containers.
- std::vector is the most popular container. It is similar to arrays, but may dynamically resize itself
- folly::fbvector is an implementation of std::vector with additional features and better performance
- std::deque is a double-ended queue. It is implemented as a sequence of fixed-size arrays.
- std::forward_list is a singly linked list, the easiest implementation of the linked list
- std::list is a more complex implementation of the linked list where nodes can reference previous nodes, and it also supports fast insertion of elements at the end of the list
Retrofitting Temporal Memory Safety on C++
Anton Bikineev, Michael Lippautz, and Hannes Payer demonstrate the use of heap scanning technologies to improve memory safety in Chrome.
Conditional members can be thought of as things that should exist conditionally in a C++20 template when certain conditions are met. In this informative article, Barry Revzin uncovers how conditional member functions, conditional member variables, and conditional member types can be implemented using C++20 concepts.
Porting Takua Renderer to 64-bit ARM- Part 1
Big hype around Apple's recent releases of the M1 chips based on ARM CPU architecture. Is it justified or is it just marketing? You decide. In any case, it seems that Apple is going to be sticking to the ARM architecture for now, and that means your software might have to start suppporting it too. In this first article of a multi-part series, Karl Li describes the motivation and issues of porting his hobby rendering software from x86 to ARM. Karl covers floating point consistency (yay fun), weak memory ordering, and a deep-dive on compilation.
unordered_multiset’s API affects its big-O
Arthur O’Dwyer discusses how "std::unordered_multiset’s decision to support .equal_range dramatically affects its performance".
Tutorial: Preparing libraries for CMake FetchContent
Jonathan Müller describes the process of making your C++ library compatible with CMake's FetchContent.
Interoperability: what's rich is still poor
Dr Stephen Kell discusses why interoperability between C and C++ is still not good, despite some improvement. The author discusses a particular programming task they carried out recently and how the lack of good interoperability made the task more difficult. The article ends with some thoughts on what good interoperability ought to mean.
- The task was writing some code to target a C-style plugin interface
- It's important to embrace "diversity" and not try to pigeonhole what interoperability should be like
- "When a coding task involves using code written in another language, we should be able to code in the native style, not just its surface syntax"
Compressing looping animation clips
Nicholas Frechette highlights the caveats of looping animations using the C++ Animation Compression Library.
C++ exceptions are becoming more and more problematic
Thomas Neumann highlights the current performance issues with C++ exceptions and proposes four potential solutions, three of which are other proposals and the last being just fixing exceptions.
C++ header files and inter-class connections
Rachel Kroll discusses some of the issues and solutions for connecting classes in C++.