Blog

Avoiding having to calculate the gcd when doing cycle decomposition -- Raymond Chen

RaymondChen_5in-150x150.jpgLast time, we looked at how clang’s libcxx implementation of std::rotate uses cycle decomposition to minimize the number of swaps. Doing so requires calculating the greatest common divisor, but I noted that the OpenJDK implementation of the java standard library uses a trick to avoid doing the gcd calculation.

Rotation revisited: Avoiding having to calculate the gcd when doing cycle decomposition

by Raymond Chen

From the article:

The trick is realizing that the total number of elements is equal to the sum of the lengths of each of its cycles, and each of the initial elements belongs to a different cycle. Therefore, we can just keep rotating elements until the number of elements rotated is equal to the total. We don’t have to precalculate the number of cycles; we just let the counter tell us when we’re done.

auto a = std::distance(first, mid); // number of "A" elements
auto n = std::distance(first, last); // total elements
auto count = 0;
auto k = 0;

while (count < n) {
    // Rotate the elements in the cycle starting at k
    auto save = std::move(first[k]);
    auto i, next = k;
    while (i = next, next = (i + a) % n, next != k) {
        first[i] = std::move(first[next]);
        ++count;
    }
    first[i] = std::move(save);
    ++count;
}

BeCPP Symposium 2026 - Phil Nash - Contemporary C++ Testing

BeCPP Symposium 2026 (organized by BeCPP): Now on YouTube!

Phil Nash - Contemporary C++ Testing

Abstract:

It's been 15 years since Catch claimed to be a "Modern C++ Testing framework". C++ has been through some game changing stages of evolution in that time. What would a test framework built for the C++ of today look like?

About the Speaker:

Phil is the original author of the C++ test framework, Catch2 and other open source libraries.
A Senior Software Engineer at Bloomberg he has had a career that spans finance, mobile and software security, with a diversion into Developer Advocacy at JetBrains and Sonar.
He's also a member of the ISO C++ standards committee, organiser of C++ London and ACCU on Sea (the merging of the ACCU conference with C++ on Sea), as well as former co-host and producer of CppCast, cpp.chat and No Diagnostic Required.

 

Elements of Concurrency -- Lucian Radu Teodorescu

logo.pngConcurrency suggests you can’t be sure what order instructions happen in. Lucian Radu Teodorescu shows how concurrency actually gives a strict partial ordering.

Elements of Concurrency

by Lucian Radu Teodorescu

From the article:

I’ve long been attracted to a quote often attributed to Einstein (whether or not he said it, it’s good advice):

Everything should be made as simple as possible, but no simpler.

I take it as a guiding principle for intellectual work on subjects with high inherent complexity. Software is one such subject; Brooks famously called it essential complexity [Brooks95]. Moreover, concurrency is one of the sharpest edges of that complexity.

I have been writing about concurrency in Overload for years, but those articles were mostly practical: tutorials, patterns, pitfalls, and implementation techniques. Here I want to step back and talk about the essence of concurrency.

I will build on the work of Tony Hoare and collaborators on the laws of programming with concurrency [Hoare09, Hoare11, Hoare13, Hoare15] (the talks are particularly enjoyable). I’ll also borrow Leslie Lamport’s viewpoint that concurrency is about the ordering of events as presented in the ‘Time, clocks, and the ordering of events in a distributed system’ article [Lamport78].

The central thesis of this article is simple: Concurrency is strict partial ordering.

Once you start seeing programs as collections of work items related by a strict partial order <, much of the apparent complexity becomes a matter of making ordering constraints explicit, manipulating them algebraically, and choosing implementations that respect them.

Some parts are a bit formal, but the payoff is a shift in perspective. Rather than treating concurrency as a bag of mechanisms (threads, locks, async, executors), we treat those mechanisms as different ways of expressing and enforcing the same ordering structure.

Rotation revisited: Cycle decomposition in clang’s libcxx -- Raymond Chen

RaymondChen_5in-150x150.jpgWe got distracted by the rotation algorithm in gcc’s libstdc++, but let’s get back to the cycle decomposition algorithm in clang’s libcxx.

Rotation revisited: Cycle decomposition in clang’s libcxx

by Raymond Chen

From the article:

The implementation in clang’s libcxx performs the minimum number of swaps, roughly n/2, where n is the total number of elements. It does so by viewing the rotation as a permutation and walking through each of the cycles.

For notational convenience, let a be |A| and n be |A| + |B| (the total number of elements). The number of cycles is gcd(a, b), and the k‘th cycle consists of the elements starting at first + k, and then stepping to the next element by moving forward another a elements, with wraparound, until you return back to the starting point.

For example, if you have |A| = 4 and |B| = 6, then the cycle that starts at A1 takes 4 steps forward to continues to B1; takes another 4 steps forward to B5; then takes 2 steps forward, wraps around, and then two more steps forward, landing on A3; then takes 4 steps forward to B3; and then takes 4 steps forward and wraps around to A1, which is the starting point.

BeCPP Symposium 2026 - Bryce Adelstein Lelbach - The CUDA C++ Developer's Toolbox

BeCPP Symposium 2026 (organized by BeCPP): Now on YouTube!

Bryce Adelstein Lelbach - The CUDA C++ Developer's Toolbox

Abstract:

Getting the most out of your GPU with C++ doesn't require writing custom kernels or manually managing storage for everything! Come learn about the libraries and techniques that make writing CUDA C++ code easier and more performant. Through examples, we'll explore all aspects of writing modern C++ software for GPUs, including heterogeneous memory management, algorithm design, and synchronization. During this talk, you'll:

  • Learn to evaluate when you should use a CUDA library versus writing your own kernel.
  • Explore popular CUDA C++ libraries such as Thrust, CUB, and libcu++.
  • Understand how you can easily compose different CUDA libraries and your own custom CUDA C++ code together.
  • Build intuition about the performance implications of CUDA libraries.
  • You'll leave confident about how to select the best tool for the job to accelerate your C++ applications for your unique use cases.

 

About the Speaker:

Bryce Adelstein Lelbach has spent over a decade developing programming languages, compilers, and libraries. He is passionate about parallel programming and strives to make it more accessible for everyone.
Bryce is a Principal Architect at NVIDIA, where he founded the Core C++ Compute Libraries team and now leads the Vanguard Programming group that drives NVIDIA's roadmap for programming languages, compilers, and core libraries.
He is a leader of the systems programming language community, having served as chair of the C++ Library Evolution and the US programming language standards committee. He has been an organizer and program chair for many conferences over the years. On the C++ committee, he has worked on concurrency primitives, parallel algorithms, senders, and multidimensional arrays.
He previously worked at Lawrence Berkeley National Laboratory and Louisiana State University. He is one of the founding developers of the HPX parallel runtime system. Outside of work, Bryce is passionate about airplanes and watches. He lives in Midtown Manhattan with his girlfriend and dog.

 

Pure Virtual C++ 2026 Is a Wrap -- Marian Luparu

That’s a wrap on Pure Virtual C++ 2026! Thank you to everyone who joined us live, asked questions in the chat, and made this year’s free, one-day C++ conference such a great time. Huge thanks to our hosts Mads Kristensen and Sinem Akinci, to every speaker who shared their work, and to the moderators who kept the conversation going.

Pure Virtual C++ 2026 Is a Wrap

by Marian Luparu

From the article:

Missed a session, or want to rewatch? All talks, both the live broadcast featured sessions and the on-demand sessions, are available now. Watch the full playlist on YouTube.

Featured sessions

These were introduced live during the broadcast, in this order:

  • C++ semantic awareness in the CLI: From Project Load to Code Change — Sinem Akinci
  • Mind The Gap: C++/Rust Interop — Victor Ciura
  • From Completions to Agents: AI-Driven C++ in Visual Studio — Augustin Popa
  • Cut Your Build Times Without Becoming a Build Expert — David Li
  • C++/WinRT: Build faster and smaller with C++20 modules — Ryan Shepherd

A shocking discovery about gcc’s unidirectional rotation algorithm -- Raymond Chen

RaymondChen_5in-150x150.jpgLast time, we looked at the rotation algorithm used by gcc libstdc++ for random-access iterators, and I concluded by noting that we’re going to make a shocking discovery.

Rotation revisited: A shocking discovery about gcc’s unidirectional rotation algorithm

by Raymond Chen

From the article:

As with all shocking discoveries, this one will shock disappoint you.

The discovery is that the gcc libstdc++ algorithm is the same as the forward-iterator algorithm!

Let’s run both algorithms on a problem where the two blocks are A1, A2, A3, B1, B2, B3, B4, B5. I’ll put the old forward iterator algorithm on top and the new gcc libstdc++ algorithm below.

first   mid       last
           
A1 A2 A3 B1 B2 B3 B4 B5
           
first   mid       last
 

We swap at first and mid, then advance both pointers. The two algorithms agree until first reaches the end of the original A block.

      first   mid   last
           
B1 B2 B3 A1 A2 A3 B4 B5
           
      first   mid   last
 

The old algorithm recurses in order to exchange A1, A2, A3 with B4, B4. This happens by exchanging A1 with B4 and A2 with B5.

Write, shorten, optimize

I stumble upon a C++ function that will be a really illustrative example of how refactoring can both shorten and optimize code. Today, we'll need to dust off our human brains in the era of vibe coding and recall what it's like to know what the good is and what the bad is—after all, someone has to do it.

Write, shorten, optimize

by Andrey Karpov

From the article:

Let's see how these implementations compare in reality. Designing a fair benchmark took a bit of effort. First, I had to ensure the input data couldn't overflow a 64-bit signed integer, since signed overflow is undefined behavior and would invalidate the measurements. Second, to make the contest fair, the test cases alternated between arrays with and without zero elements. Finally, the input arrays had varying lengths.

I'm not claiming that the measurements are rigorous, but they represent a general idea. The speed of the first original algorithm is taken as the baseline. I used Clang with the -O2 and -m64 options. The original version with two loops: 1. My version with a single loop: 0.88. The Claude version with a single multiplication: 0.92.

 

Rotation revisited: Another unidirectional algorithm -- Raymond Chen

RaymondChen_5in-150x150.jpgSome time ago, we looked at how to swap two adjacent blocks of memory in constant extra space, and along the way explored how std::rotate accomplishes the same task. I later claimed that the random-access implementations in both libc++ and libstdc++ treat the operation as a permutation decomposed into cycles—but after taking a closer look, I discovered that only libc++ does; libstdc++ uses a different algorithm altogether.

Rotation revisited: Another unidirectional algorithm

by Raymond Chen

From the article:

Some time ago, we looked at the problem of swapping two blocks of memory that reside inside a larger block, in constant memory, and along the way, we learned about std::rotate which swaps two adjacent blocks of memory (not necessarily the same size).

I noted in a postscript that clang’s libcxx and gcc’s libstdc++ contain specializations of std::rotate for random-access iterators that view the operation as a permutation and decomposes the permutation into cycles.

I was mistaken.

The implementation in gcc’s libstdc++ has special cases for single-element rotations, but in the general case, it uses a different algorithm.

Let’s call the blocks of memory to be exchanged A and B, where A is made up of elements A1, A2, A3, and so on; and block B has elements B1, B2, B3, and so on. Without loss of generality, suppose the A block is smaller. (If not, we can just mirror the algorithm.) And for concreteness let’s say that the elements are A1, A2, A3, B1, B2, B3, B4, B5.

C++ More C++26 reflection at compile-time -- Andreas Fertig

797f4c8c0b89b22b.pngIn today's post, I like touch-up on C++26's static reflection. In case you haven't seen, I wrote a first post C++26 reflection at compile-time a while ago.

C++ More C++26 reflection at compile-time

by Andreas Fertig

From the article:

One of the great things about reflection is that we can already explore the new feature since with Clang there is a compiler available that implements all the facets.

I was again exploring what of my use cases would be better solved with reflection. Now, one thing that I had to do most of my career is reading and writing data coming from a network connection. The definition of network was different at different times. What was common is, that everything going out was sent in network byte order (big-endian), and the everything that was received arrived in network byte order as well. For some systems there was no difference, as they where already big endian machines. But not all the time. Especially ARM pushed little endian. For a subset of the systems data had to be byte-swapped when it was received or sent.

How to swap data?

The issue here (was) is, how to swap the data? Every data type larger than a byte must be swapped every time. C++23 gave us std::byteswap which removes the need for the POSIX functions like htons. At least an improvement in terms of safety.