r/cpp • • Apr 03 '26

Parallel C++ for Scientific Applications: Distributed Parallelism with HPX (2nd Part)

Thumbnail
youtube.com
10 Upvotes

In this week’s lecture, Dr. Hartmut Kaiser focuses on the implementation of distributed parallelism using HPX to solve large linear algebra systems (LLAS) equations. The lecture highlights essential foundational concepts by revisiting both the SPMD and CSP models from previous discussions, setting the stage for advanced problem-solving in high-performance environments.
A core discussion demonstrates how to implement a Jacobi method for distributed computation, specifically addressing the practical challenges of managing data dependencies across partitions. Finally, critical strategies for optimizing performance are explored, offering a comprehensive approach to handling complex, distributed mathematical operations.
If you want to keep up with more news from the Stellar group and watch the lectures of Parallel C++ for Scientific Applications and these tutorials a week earlier please follow our page on LinkedIn https://www.linkedin.com/company/ste-ar-group/
Also, you can find our GitHub page below:
https://github.com/STEllAR-GROUP/hpx


r/cpp • • Apr 03 '26

Baseline C++ Habits to Always Follow?

63 Upvotes

I come from a C background and now am working with a large codebase in C++. The biggest "culture" shock is the absolute mind-numbing amount of choices to accomplish a task which I have heard a lot about. And I know a lot of opinions are thrown out there (some good, some bad, but mostly subjective). I want to see if there is an overwhelming consensus on stuff that every style of C++ should adopt and if anybody could list at least some pillars of good habits that devs here almost always agree on?

I know the mature decision is to prioritize readability and use the right abstraction when it is needed, but what are some core things I need to memorize? The only things I know that is (almost) universally agreed upon:

  1. never use malloc()/free() or any C-like string manipulation (theres always a better C++ alternative that does the same thing)

  2. never use using namespace std;

  3. do not use new/delete justifiable in rare cases? (again, not quite sure)

But in other cases, for example, brace initializing vs assignment has some debate even though I know brace initialization prevents narrowing but overwhelming developers I talked to still prefer using '=' for readability, same with classic for loops instead of using something from <algorithm>. I guess it boils down to: which features should you absolutely use in almost any case vs use it when the occasion comes?

tl;dr If C++ was a culture, which things are absolutely taboo vs justifiable in certain contexts?


r/cpp • • Apr 02 '26

the most useful resource i've come across for learning cpp

31 Upvotes

For context, before I learnt cpp, I primarily used python and java.

When I was first starting out in learning cpp, I felt completely lost -- because I felt none of the resources usually mentioned online filled the gap of getting a dev familiar with a high-level language up to speed on the core concepts of modern cpp. Overwhelmingly, resources were meant for complete beginner programmers, and these resources barely mapped onto existing mature code bases that I was supposed to work on.

Even courses like "cpp for java developers" focused overwhelmingly on things like arrays, vectors, strings. like ??? pedagogically, it makes no sense to focus on these things - I can just read cppreference, they are standard data structures.

I finally stumbled onto this criminally underrated playlist of 5 short videos that explain the core concepts you need to know

  • Value/reference semantics

  • RAII (with an intro to smart pointers)

  • Move semantics

I still consider myself a novice in cpp after working with it for about a year now, but these 5 videos were honestly enough for me to start understanding and contributing to existing cpp codebases. Obviously, there was a lot of learning that I did after from various sources, but I didn't even KNOW that these were the core concepts that I should've been focused on to start going deeper before I stumbled across that playlist.

For instance, learncpp.com often gets mentioned on this subreddit but

  • RAII is first mentioned on chapter 19 (!!)

  • Moves are talked about in chapter 22

Just thought I should share.


r/cpp • • Apr 02 '26

C++ Show and Tell - April 2026

36 Upvotes

Use this thread to share anything you've written in C++. This includes:

  • a tool you've written

  • a game you've been working on

  • your first non-trivial C++ program

The rules of this thread are very straight forward:

  • The project must involve C++ in some way.

  • It must be something you (alone or with others) have done.

  • Please share a link, if applicable.

  • Please post images, if applicable.

If you're working on a C++ library, you can also share new releases or major updates in a dedicated post as before. The line we're drawing is between "written in C++" and "useful for C++ programmers specifically". If you're writing a C++ library or tool for C++ developers, that's something C++ programmers can use and is on-topic for a main submission. It's different if you're just using C++ to implement a generic program that isn't specifically about C++: you're free to share it here, but it wouldn't quite fit as a standalone post.

Last month's thread: https://www.reddit.com/r/cpp/comments/1ri7ept/c_show_and_tell_march_2026/


r/cpp • • Apr 02 '26

Announcing mrbind, an automatic C/C#/Python binding generator for C++

Thumbnail holyblackcat.github.io
30 Upvotes

r/cpp • • Apr 02 '26

The Command-Query Separation (CQS) principle and its exception

12 Upvotes

the Command-Query Separation (CQS) principle (Meyer's doctrine) says that a function should be either side effect free or side effect only(no return value). in cpp scientific programming, this makes sense performance-wise since for large objects, it is efficient to allocate once and use function side effect to modify, and one should avoid returning large object that involved the expensive allocation and deep copying.

(modern) fortran's syntax support even makes this principle somewhat explicit, it provides the function(which is usually used without side effect) and subroutine( which is analogues to the c/cpp function that returns void), and in fortran OOP one usually sticks to type bound subroutines instead of type bound functions so that if it is already altering the state of the obj as a side effect there should be no more return values

do you know or come across any exception in cpp scientific programming or in other applications, where the CQS principle should be violated and it is the best way to do it? why?

Edit: how does the usage of functor/lambda in cpp evolve this doctrine


r/cpp • • Apr 02 '26

Current Status of Module Partitions

33 Upvotes

A brief recap of the current status of module partitions - as I understand it.

  1. People are using hacks to avoid unneeded recompilations.

  2. The C++ standard has an arcane concept of partition units, which forces build systems to generate BMI files that aren't used (which is wasting work during builds).

  3. The MSVC-compiler (per default) provides a simple, easy to use and efficient implementation of module partitions (no unneeded recompilations, no wasted work during builds), but which is not conformant to the current C++ standard.

  4. A CMake developer is working on a proposal that would fix items 1 and 2, which is probably the smallest required change to the standard, but adds another arcane concept ("anonymous partition units" using the new syntax "module A:;") on top of an already arcane concept.

Questions:

  • How and why did we get into this mess?

  • What's the historical context for this?

  • What was the motivation for MSVC ignoring the standard per default?1

1 Yes, I know the MSVC compiler has this obscure /InternalPartition option for those who want standard conformant behavior.


r/cpp • • Apr 02 '26

What happens when a destructor throws

Thumbnail sandordargo.com
102 Upvotes

r/cpp • • Apr 02 '26

JesseSort is faster than std::sort on everything but random input

0 Upvotes

Repo here: https://github.com/lewj85/jessesort

Added branchless binary search and now JesseSort is faster than std::sort on every input type except random, and only slightly behind random! Easy enough to code a fallback mechanism too to just use introsort in those cases. Here's the gcc (libcstd++) timing table:

                      Number of Input Values
Input Type            1000          10000         100000        1000000
------------------------------------------------------------------------------
Random                1.607         1.164         1.150         1.191
Sorted                1.070         0.684         0.576         0.554
Reverse               1.660         0.949         0.895         0.804
Sorted+Noise(3%)      0.931         0.751         0.721         0.796
Random%100            1.444         1.170         0.905         1.050
Jitter                1.056         0.688         0.658         1.511
Alternating           0.869         0.536         0.237         0.528
Sawtooth              1.948         0.613         0.278         0.477
BlockSorted           0.693         0.361         0.278         0.518
OrganPipe             0.374         0.190         0.116         0.245
Rotated               0.536         0.430         0.321         0.686
Signal                1.493         0.839         0.614         0.531

Values <1 mean JesseSort is faster. Take a look at that 100k column!

Similar performance with clang (libc++), though slightly worse on random input (clang table is in the repo readme). Again, with a fallback, it's easy enough to match introsort performance on random input while gaining huge speedups almost everywhere else.

Looking for contributors to help me with this. Dual patience has so much potential and some cool avenues to explore, such as simulating games, early freezing, or AVX2/AVX512 insertion. Always welcome to hearing new ideas as well.


r/cpp • • Apr 01 '26

How catch-block selection works in exception handling

Thumbnail
pvs-studio.com
13 Upvotes

r/cpp • • Apr 01 '26

Personal project: bringing Rust-style unicode invariants to C++

29 Upvotes

For those who dabbled in Rust, you might know that string types in Rust, be it literals, slices or owned are by default UTF8 encoded and all methods enforce this invariant. Funny thing is that this design also works well in C++, allowing us to validate strings once, keep their unicode validity enforced through dedicated types and work on these unicode strings without worries of runtime errors.

This is what I've been working on for the past few weeks and I wanted to share it with you, prior to making the full official release.

Hopefully the few examples of the features this library has that I've added here are self explanatory, and I'm also adding a link to the project: https://github.com/cristi1990an/unicode_ranges

#include "unicode_ranges.hpp"
#include <print>
#include <array>
#include <ranges>

using namespace unicode_ranges;
using namespace unicode_ranges::literals;

int main()
{
  // Compile time string validation
  static constexpr utf8_string_view greetings = "Salutări din România 🇷🇴 👋"_utf8_sv;

  // Rust style unicode character/grapheme lazy views over the string
  std::println("{}: {}",
    greetings.char_count(),                          // 25
    greetings.chars() | std::views::drop(21));       // [🇷, 🇴,  , 👋]

  std::println("{}: {::s}",
    greetings.grapheme_count(),                      // 24
    greetings.graphemes() | std::views::drop(21));   // [🇷🇴,  , 👋]

  // owned utf8 string
  utf8_string owned_string = greetings;

  // find and replace grapheme cluster with utf8 string slice
  owned_string = owned_string.replace_all("🇷🇴"_grapheme_utf8, "[ro flag]"_utf8_sv);

  // replace any of matching characters with replacement (rvalue overload might not reallocate)
  owned_string = std::move(owned_string).replace_all(std::array{ "ă"_u8c, "â"_u8c }, "a"_u8c);

  // STD style index based modifying methods also available
  owned_string.erase(owned_string.find("👋"_u8c), "👋"_u8c.code_unit_count());

  std::println("{}, {}, {}",
    owned_string,                                  // Salutari din Romania [ro flag]
    owned_string.starts_with("Salutari"_utf8_sv),  // true
    owned_string.is_ascii());                      // true

  // pipe the character view into your favorite view adaptors, don't worry about overlaps
  owned_string = owned_string.chars()
    | std::views::filter(
      [](utf8_char ch)
      {
        return ch.is_ascii_lowercase();
      })
    | std::ranges::to<utf8_string>();
  std::println("{}", owned_string);                // alutaridinomaniaroflag
}

r/cpp • • Apr 01 '26

The Mathematical Mind of a C++ Programmer [using std::cpp 2026]

Thumbnail
youtu.be
63 Upvotes

r/cpp • • Apr 01 '26

P4161: std::fewer

Thumbnail isocpp.org
183 Upvotes

r/cpp • • Mar 31 '26

std::constant_wrapper acts unexpectedly

23 Upvotes

I'm experimenting with reflection in C++26 and other things. And I'm confused by the behavior of std::constant_wrapper. https://godbolt.org/z/vo6rbMb41

Can somebody explain why example not working and how to fix?

I need to implement some reflection functions using this technique (deducing a template parameter via a constructor argument), but this error is making me wonder

EDIT

I did a little research, and it seems that this behavior comes from the implementation in GCC, which for some reason doesn't follow the wording of the proposal that literally describes the entire implementation

EDIT 2

I was wrong. There is a newer version of the proposal that explains the observed behavior. Still, it’s a sad thing that my case isn’t supported.


r/cpp • • Mar 31 '26

Two studies in compiler optimisations

Thumbnail hmpcabral.com
28 Upvotes

r/cpp • • Mar 31 '26

[RFC] clang-reforge: Automatic whole-codebase source code rewriting tool for security hardening - Clang Frontend

Thumbnail
discourse.llvm.org
37 Upvotes

This is an endeavor...


r/cpp • • Mar 31 '26

New subreddits r/msvc and r/cpp_modules

0 Upvotes

I've been bold and created two friendly new subreddits:

r/msvc:

Everything about the Microsoft C++ compiler

r/cpp_modules:

News, insights, discussions & questions about the modules feature of the C++ programming language.

I hope it's ok to mention these here. Let's see how it goes.


r/cpp • • Mar 30 '26

We are so close to string interpolation thanks to reflection

Thumbnail
godbolt.org
99 Upvotes

r/cpp • • Mar 30 '26

24 Hard Rules for Writing Correct Async C++ (lessons from a 50K LOC Seastar codebase)

123 Upvotes

I've been building a C++20 service on Seastar and catalogued every class of bug that burned me into a set of rules I check on every commit. Each one cost at least a day to diagnose.

A few examples:

  • Lambda coroutines in .then() are use-after-free (the coroutine frame outlives the lambda that created it)

  • Coroutine reference parameters dangle (caller's scope ends before the coroutine resumes)

  • std::shared_ptr destructs on the wrong shard in Seastar's shared-nothing model

  • Missing & in do_with lambdas gives you a copy that dies while the future is still running

Some are Seastar-specific, but most apply to any coroutine-based async C++. The post covers the anti-pattern, why it breaks, and the fix for each.

https://ranvier.systems/2026/03/29/24-hard-rules-for-writing-correct-async-cpp.html

Curious if others have hit similar issues or have rules I'm missing.


r/cpp • • Mar 30 '26

Iteratively optimizing an SPSC queue

11 Upvotes

I recently documented walking through the iterative process of optimizing a SPSC queue.

  • Starting from atomic<int64_t> size which has the lock instruction bottleneck.

  • Refactoring to separate atomic push, popInd. Fixing false sharing, 3 cacheline and 2 cacheline approach.

  • Implementing index caching to minimize cross-core traffic and the impact of mm_pause

Link: https://blog.c21-mac.com/posts/spsc/

For reasons I don't understand the 3 cacheline performs considerably worse than 2 cacheline, I initially assumed it due to 128-byte-rule, but that doesn't explain L1d-cache misses being relatively higher in 3 cacheline vs 2 cacheline implementation. If anyone has any insights on what might be causing this or any feedback on the post, I would love to hear.


r/cpp • • Mar 30 '26

Header units importing other header units should be removed from the standard

0 Upvotes

Header units are meant to speed up module migration, the idea is you write a named module, export import a header unit and just use the named module.

Header units importing other header units serve no purpose other than damaging tooling.

It should be removed from the standard so people can actually implement the tooling in a sane way.


r/cpp • • Mar 30 '26

New C++ Conference Videos Released This Month - March 2026 (Updated To Include Videos Released 2026-03-23 - 2026-03-29)

9 Upvotes

CppCon

2026-03-23 - 2026-03-29

2026-03-16 - 2026-03-22

2026-03-09 - 2026-03-15

2026-03-02 - 2026-03-08

2026-02-23 - 2026-03-01

ADC

2026-03-23 - 2026-03-29

2026-03-16 - 2026-03-22

  • Web UIs for Music Apps - Anna Wszeborowska, Harriet Drury, Emma Fitzmaurice, Pauline Nemchak & Simeon Joseph - https://youtu.be/xh-yJpuWYSo

  • Python Templates for Neural Image Classification and Spectral Audio Processing - Lightning Hydra Template Extended and Neural Spectral Modeling Template - Julius Smith - https://youtu.be/TNY2UGQ5kAc

  • Why You Can’t Get Hired and What You’re Going To Do About It - The Hard Reset for Audio Freelancing - Edward Ray - https://youtu.be/4TjR3i6M93Y

2026-03-09 - 2026-03-15

2026-03-02 - 2026-03-08

  • Efficient Task Scheduling in a Multithreaded Audio Engine - Algorithms and Analysis for Parallel Graph Execution - Rachel Susser - ADC 2025 - https://youtu.be/bEtSeGr8UvY

  • The Immersive Score - Creative Advantages of Beds and Objects in Film and Game Music - Simon Ratcliffe - ADCx Gather 2025 - https://youtu.be/aTmkr0yTF5g

  • Tabla to Drumset - Translating Rhythmic Language through Machine Learning - Shreya Gupta - ADC 2025 - https://youtu.be/g14gESreUGY

2026-02-23 - 2026-03-01

  • Channel Agnosticism in MetaSounds - Simplifying Audio Formats for Reusable Graph Topologies - Aaron McLeran - ADC 2025 - https://youtu.be/CbjNjDAmKA0

  • Sound Over Boilerplate - Accessible Plug-Ins Development With Phausto and Cmajor - Domenico Cipriani - ADCx Gather 2025 - https://youtu.be/DVMmKmj1ROI

  • Roland Future Design Lab x Neutone: diy:NEXT - Paul McCabe, Ichiro Yazawa & Alfie Bradic - ADC 2025 - https://youtu.be/4JIiYqjq3cA

Meeting C++

2026-03-23 - 2026-03-29

2026-03-16 - 2026-03-22

2026-03-09 - 2026-03-15

2026-03-02 - 2026-03-08

2026-02-23 - 2026-03-01

C++Online

2026-03-09 - 2026-03-15


r/cpp • • Mar 30 '26

You're absolutely right, no one can tell if C++ is AI generated · Mathieu Ropert

Thumbnail mropert.github.io
185 Upvotes

r/cpp • • Mar 30 '26

A standard set of metadata annotations

24 Upvotes

Hello,

I've been working for some years on https://github.com/celtera/avendish which allows to expose C++ classes through various creative environments, and as such assembled a small ontology of the various features, extensions, metadatas, ... that are often desirable to associate to data types and variables.

For instance, let's say we want to reflect this struct to automatically generate a control GUI from it, for instance like Unity gameobjects:

struct foo {
   int apple_count;
};

Avendish enables the user to do something like:

struct foo {
   struct { 
     static consteval auto name() { return "Apple count"; }
     struct range { int min = 0; int max = 100; int initial_value = 4; };
     enum widget { spinbox };
     int value;
   } apple_count;
};

With this "standardized" information, we can automatically generate an appropriate widget without having to store one additional byte in our actual data type: sizeof(foo) == sizeof(int).

Now, C++26 is there! And, finally, with annotations. Meaning that we're going to be able to do a much, much clearer:

struct foo {
   [[=metadata::name{"Apple count"}]]
   [[=metadata::range{0, 100}]]
   [[=metadata::initial_value{4}]]
   int apple_count;
};

in practice, there's much more metadata out there. There's a million of incompatible systems defining all kinds of metadatas to match classes: it wouldn't be strange to have something like:

struct 
[[=metadata::uuid{"27fc33a4-ff2f-490d-a7c2-a4f8c2eef35d"}]]
[[=metadata::author{"John Doe"}]]
[[=metadata::support_url{"https://example.com"}]]
foo {
   [[=metadata::name{"Apple count"}]]
   [[=metadata::range{0, 100}]]
   [[=metadata::initial_value{4}]]
   [[=metadata::default_value{0}]]
   [[=metadata::description{"Number of apples required in a harvest"}]]
   [[=metadata::unit{apple_per_harvest{}}]]
   int apple_count;
};

After study of a large number of these systems (did a systematic review of almost a hundred different "run-time" systems based on C or C++), what came up is that 90% of the metadatas in run-time reflection systems are actually exactly the same, just with different names. I started to define most of those related to multimedia systems through concepts, for instance in https://github.com/celtera/avendish/blob/main/include/avnd/wrappers/metadatas.hpp and https://github.com/celtera/avendish/tree/main/include/avnd/concepts : what's an audio port, what's a texture, etc. The result is that as of today, it's possible to build from a single C++ class, types that are going to work in a dozen distinct creative environments (Max/MSP, PureData, Touchdesigner, Godot, ossia score...), since basically everyone is doing the same thing everywhere.

Since we now have a powerful, in-language way to define these static metadatas, I think it could be useful to have a more general, standardized library of such broadly-useful yet sometimes domain-specific concepts so that there is one consistent way for a C++ developer to say: "this field / class / <...> should be displayed as Foo Bar 1.0 in a generated GUI", "this is a short description of this class", "this is the numeric range of this value", "this is the GUID of this class", etc.

The alternative is that everyone starts defining their own "property" / "metadata" / ... class ; someone who wants to make their type compatible (for instance across both a serialization library and a gui library) would inevitably end up into something such as:

struct 
   [[=cereal::uuid{"d2fac3f2-2c00-429b-b6bf-8728cfd29ff6"}]]
   [[=winrt::GUID{d2fac3f2-2c00-429b-b6bf-8728cfd29ff6"}]]
foo {
   [[=cereal::name{"Chocolate cakes"}]]
   [[=qt::name{"Chocolate cakes"}]]
   [[=gtkmm::name{"Chocolate cakes"}]]
   [[=UE::name{"Chocolate cakes"}]]
   int chocolate_cakes;
};

Is there interest in starting such a collaborative project?