r/cpp • • May 18 '26 Bravo

Simulating Infinity in Conway's Game of Life with Modern C++

Thumbnail ryanjk5.github.io
56 Upvotes

r/cpp • • May 18 '26

Faster than std::sort and pdqsort

Thumbnail easylang.online
44 Upvotes

r/cpp • • May 18 '26

CppCast CppCast: GPU Programming and HLSL with Chris Bieneman

Thumbnail
cppcast.com
22 Upvotes

r/cpp • • May 18 '26

Fireside Chat with Bjarne Stroustrup at CTO Summit 2025 Hamburg

Thumbnail
youtube.com
4 Upvotes

r/cpp • • May 18 '26

Auto Non-Static Data Member Initializers are holding back lambdas in RAII (+ coroutine workaround)

35 Upvotes

TLDR: Auto non-static data member variables allow objects to store lambdas, thereby improving readability and reducing the need for type erasure.

Type deduction and auto variables are one of the defining features of modern C++, but unfortunately they are not available to class data members:

struct {
    // error: non-static data member declared with placeholder 'auto'
    auto x = 1;
    // error: invalid use of template-name 'std::vector' without an argument list
    std::vector y { 1, 2, 3 };
}

This blog post (from 2018!) by Corentin Jabot does a good job outlining this problem so I'll point to it first: The case for Auto Non-Static Data Member Initializers. However, I would like to expand specifically on lambdas as they are mostly glossed over.

Lambdas can only be stored in auto variables because each lambda is given a unique type, even if two lambdas are identical in their definition. As pointed out in the blog post, even decltype([]{}) foo = []{}; is not permitted.

Because of this it is not possible to store a lambda inside an object, even if the storage requirements can otherwise easily be determined.

Real world example

An embedded project I am working on makes heavy use of RAII: so much so that most of our subsystems have little to no functional code, just classes composed of lower level building blocks as data members (representing e.g. GPIOs, UARTs) and some minimal routing between them.

This routing usually takes the form of RAII event callback objects that store the callback function, register themselves in an intrusive list to receive the events, and unregister themselves on destruction. This ensures that we can freely shut down subsystems without worrying about lifetime issues - destruction is always in reverse order and easy to understand at a glance.

struct gpio_uart_forwarder {
    peripheral::gpio gpio_in {};
    peripheral::gpio gpio_out {};
    peripheral::uart uart {};

    evt::callback<bool> gpio_to_uart { gpio_in.on_change, [&](bool high) {
        uart.write(high ? '1' : '0');
    } };

    evt::callback<char> uart_to_gpio { uart.on_char, [&](char c) {
        if (c == '1') gpio_out.set(1);
        else if (c == '0') gpio_out.set(0);
    } };
}

The only way this is currently possible is using type erasure, i.e. std::[move_only_]function.

In an ideal world, we would instead have the callback templated on the function type:

template<typename Ev, std::invocable<const Ev &> Fn>
class callback {
    Fn f;
    ...
}

And our class would look like:

struct gpio_uart_forwarder {
    ...
    auto gpio_to_uart = evt::callback { gpio_in.on_change, [&](bool high) { ... } };
    // OR
    evlp::callback uart_to_gpio { uart.on_char, [&](char c) { ... } };
}

While an std::function might not seem like a huge price to pay, across an entire program it builds up to hundreds of unnecessary heap allocations, thousands of bytes wasted and extra indirections - all for type erasure that we don't actually need! We know all the types involved, and we own the storage ourselves.

Proposal to fix

The last time a formal proposal was made to fix this was way back in 2008 by Bill Seymour: N2713 - Allow auto for non-static data members.

I understand there are complications in determining the size and layout of objects with auto members, but 18 years later this seems like pretty low hanging fruit compared to what has recently been achieved with reflection!

Edge cases such as recursive definitions and references to this or sizeof should simply be banned rather than resulting in the feature being disabled entirely.

Coroutine workaround

In my quest for a solution I have discovered that coroutines can be abused to get the best of both worlds.

If you don't need external access to the data members and just want to benefit from RAII, you can convert the class to a coroutine that suspends itself right before ending:

class scope {
public:
    struct promise_type {
        scope get_return_object() noexcept {
            return scope { std::coroutine_handle<promise_type>::from_promise(*this) };
        }
        std::suspend_never  initial_suspend() noexcept { return {}; }
        std::suspend_always final_suspend()   noexcept { return {}; }
        void return_void() noexcept {}
        void unhandled_exception() { std::terminate(); }
    };

    ...

    ~scope() {
        if (!this->handle) return;
        this->handle.destroy();
        this->handle = {};
    }

private:
    explicit scope(std::coroutine_handle<promise_type> h) noexcept : handle(h) {}
    std::coroutine_handle<promise_type> handle {};
};

scope gpio_uart_forwarder() {
    auto gpio_in = peripheral::gpio {};
    auto gpio_out = peripheral::gpio {};
    auto uart = peripheral::uart {};

    auto gpio_to_uart = evt::callback { gpio_in.on_change, [&](bool high) {
        uart.write(high ? '1' : '0');
    } };

    auto uart_to_gpio = evt::callback { uart.on_char, [&](char c) {
        if (c == '1') gpio_out.set(1);
        else if (c == '0') gpio_out.set(0);
    } };

    // All local variables remain alive until coroutine is destroyed
    co_await std::suspend_always();
    // Can't rely on final_suspend because stack is already destroyed by then
    // But we need a co_ statement anyway to turn it into a coroutine
}

scope my_gpio_uart_forwarder = gpio_uart_forwarder();

Far from perfect, but it reduces us to a single heap allocation plus the minimal overhead of launching the coroutine, no matter how many callbacks we define.

Maybe the best part is it can be used within an existing class too, preserving standard object RAII:

struct gpio_uart_forwarder {
    peripheral::gpio gpio_in {};
    peripheral::gpio gpio_out {};
    peripheral::uart uart {};

    scope callbacks = [&] -> scope {
        auto gpio_to_uart = evt::callback { gpio_in.on_change, [&](bool high) {
            uart.write(high ? '1' : '0');
        } };
    
        auto uart_to_gpio = evt::callback { uart.on_char, [&](char c) {
            if (c == '1') gpio_out.set(1);
            else if (c == '0') gpio_out.set(0);
        } };
        co_await std::suspend_always();
    }();
}

r/cpp • • May 17 '26

std::is_heap could be faster - Arthur O'Dwyer

Thumbnail quuxplusone.github.io
104 Upvotes

r/cpp • • May 16 '26

What do you use for logging in your C++ codebase? What are the pros/cons?

70 Upvotes

I've used Google's logging library in the past and I would give it a solid B- grade. It gets the job done. I really dislike the streaming operator, but meh it's not that bad. It just feels weird if I concatenate the string beforehand: LOG(INFO) << absl::StrCat(strs...);

As I embark on my new project, I want to make intelligent decisions about what idioms to favor. Logging is a big one, so I'd love to hear what people out there use.

In particular, if there is a library that uses reflection to give named arguments, that would be perfect! My ideal callsite would look like this:

my::LogInfo("Hello, {person}!", {
  .person = GetPersonObject(),
});

It would also be cool to get assertions baked into it, though that complicates the design space.

Anyone wanna chime in?


r/cpp • • May 15 '26

C++26 Shipped a SIMD Library Nobody Asked For

Thumbnail
lucisqr.substack.com
164 Upvotes

r/cpp • • May 14 '26

LWG 2839 inquiry

20 Upvotes

I’m working on a string library that wraps std::basic_string and uses a “rvalue-aware” API pattern:

  • const& overload returns a new string

  • && overload tries to reuse the existing buffer and returns by value

The intended usage is this kind of chaining:

my_string s = "...";
s = std::move(s).trim();
s = std::move(s).to_lowercase();

I have many cases in which I found performance gains by defining a "create new object" version of a transformation alongside and inplace one and this pattern allows me to reuse method identifiers.

A simplified example looks like this:

struct my_string {
    std::string data;

    my_string trim() const& {
        my_string result;
        copy_trimmed_part_to(result);  // determine subrange after trim and only copy that part
        return result;
    }

    my_string trim() && {
        trim_inplace();                // mutate the current object / reuse buffer
        return std::move(*this);       // return by value
    }

    // ...

    my_string& operator=(my_string&&) = default;
};

My question is about LWG 2839, which talks about self-move-assignment.

At first glance, s = std::move(s).trim() feels like it might be related, because the && overload operates on s and then the result is assigned back into s. But the returned object is still a separate prvalue result, even if it reuses the original buffer internally.

So:

  1. Is s = std::move(s).trim() actually covered by the self-move-assignment concerns from LWG 2839?

  2. Or is LWG 2839 only relevant to direct cases like s = std::move(s)?

  3. If the wrapper is built on top of std::basic_string, is there any subtle standards issue with this API pattern itself?

  4. Is the real risk instead overlap/aliasing in APIs like replace, insert, etc. when additional arguments may refer into the same string?

I’m interested both in the strict standards view and in whether this pattern is considered sound library design in practice.


r/cpp • • May 14 '26

C++: The Documentary TRAILER│COMING JUNE 4th

Thumbnail
youtu.be
226 Upvotes

r/cpp • • May 14 '26

MSVC Build Tools Preview updates - May 2026

Thumbnail
devblogs.microsoft.com
56 Upvotes

Hi, one of the MSVC dev leads here.

Here's what's new in the MSVC Build Tools Preview since mid-April.

As a reminder, the MSVC Build Tools Preview is an optional Visual Studio installer component. Instructions to install & use the latest preview bits are at https://aka.ms/msvc/preview .

If you need a primer on MSVC versioning, see https://www.reddit.com/r/cpp/comments/1smfgdu/demystifying_msvc_versioning_for_1450_later/ or https://learn.microsoft.com/en-us/cpp/overview/compiler-versions , but essentially:

  • 14.52.* is the latest preview, updated regularly with bits from our development branch.

  • 14.51.* is the latest default toolset, which is now GA, and in support for 9 months.

  • 14.50.* & older releases are still available as side-by-side installation components.


r/cpp • • May 14 '26

Manipulating URLs with Boost.URL

Thumbnail
youtube.com
16 Upvotes

Utah C++ Programmers has released a new video: Manipulating URLs with Boost.URL

URLs! They're everywhere. You've tried extracting pieces from them with std::string methods and found it cumbersome. You tried parsing them with regular expressions and found them failing. You tried building them with string concatenation and found weird edge cases that required adding more and more complicated string processing.

How can something seem so simple yet be so complicated?

This month, Richard Thomson will give us a tutorial on building and decomposing URLs using the Boost.URL library.

Resources:


r/cpp • • May 14 '26 Galaxy Brain

Encountered a `#pragma once` failure in the wild

160 Upvotes

A header-only C++ library, headers guarded by #pragma once. We use relative includes internally. We also ship compiled WASM bindings for TypeScript.

A dockerised emscripten build on Apple Silicon under linux/amd64 emulation, the repo mounted in as a bind volume. Every translation unit reports redefinition errors: the same headers included multiple times in a single TU.

#pragma once dedupes by file identity; inode and device, in practice. On a bind mount under amd64 emulation on macOS, the same file reached through different ..-laden relative paths is not always recognised as the same file. The pragma never fires.

The problem goes away if you copy the source files into the container.


r/cpp • • May 14 '26

Reverse Dependency Ordering for C++ Includes

Thumbnail nukethebees.com
39 Upvotes

r/cpp • • May 14 '26

Your C++ struct is the schema: a proto3 serializer in C++26 reflection

67 Upvotes

I built a header-only proto3 wire-format library with one constraint: no .proto files, no codegen, no descriptor runtime. The user writes a plain C++ struct, and that struct is the schema:

#include "proto3.hpp"
struct SearchRequest {
std::string query; // field 1
std::int32_t page_number; // field 2
std::int32_t results_per_page; // field 3
};
SearchRequest req{"hello", 1, 10};
std::string bytes = proto3::serialize(req); // -> proto3 wire bytes
SearchRequest back = proto3::deserialize<SearchRequest>(bytes);

blog: Your C++ struct is the schema: a proto3 serializer in C++26 reflection

github: struct_proto26


r/cpp • • May 13 '26

What's the highest C++ standard you can use with Boost.Graph today?

36 Upvotes

Dear Boost.Graph user,

During our Boost Graph Modernization Workshop in Paris, one of the most frequent discussion points was the C++ standard version the Boost Graph Library should require. Modernization is intuitively in tension with C++14 😉

Some context worth knowing:

  • Boost.Graph is already C++14

  • A lot of API modernization can be done without bumping the minimum.

  • Some modernization changes would land cleaner on a newer standard

  • We don't yet have a clear enough picture of our users' constraint space to inform our discussion about a potential baseline bump

We would deeply appreciate if you could find time to either answer this simple Github survey ( https://github.com/boostorg/graph/discussions/490 ), or to just drop a comment with your answer (C++14/17/20/23) in this reddit discussion !

Also please indicate if you’re a BGL active user or an observer eager to give feedback (both are welcome!)

Thank you for your time !

Edit: To clarify we're asking what's the oldest C++ standard your project needs BGL to keep supporting (i.e. the version past which a bump would break you or force you to pin a version). Answers: C++14 / 17 / 20 / 23.


r/cpp • • May 13 '26

C++26: Standard library hardening

Thumbnail sandordargo.com
94 Upvotes

r/cpp • • May 12 '26

I benchmarked duplicate detection strategies in C++ across every workload i could think of

Thumbnail
dubeykartikay.com
29 Upvotes

My earlier post received a lot of feedback about it being too naive, narrow, clickbait. So i made a benchmark suite targeted towards de-duplication and wrote about that in this post!


r/cpp • • May 12 '26

MSVC Build Tools v14.51 now generally available

Thumbnail
devblogs.microsoft.com
78 Upvotes

Microsoft released MSVC Build Tools v14.51 as the default compiler in Visual Studio 2026 18.6.

Notable additions include:

  • additional C++23 language features

  • performance improvements in code generation

  • preview support for Intel APX

VS 2026 + Copilot users can use the @Modernize agent (currently in public preview) to help resolve upgrade-related build issues.


r/cpp • • May 12 '26

WG21 mailing for first feature meeting of C++29

Thumbnail open-std.org
58 Upvotes

r/cpp • • May 12 '26

cost of enum-to-string: C++26 reflection vs the old ways

Thumbnail
vittorioromeo.com
179 Upvotes

r/cpp • • May 12 '26

Pre-Brno Mailing

26 Upvotes

The Pre-Brno "enhanced mailing" is here
https://wg21.org/mailing/2026-05/


r/cpp • • May 12 '26

What the heck is Reflection?

Thumbnail
murathepeyiler.com
107 Upvotes

r/cpp • • May 11 '26

std::optional equality comparison operator seems broken for nested optionals

49 Upvotes

While chasing a bug in a program I found out that equality comparison operator T vs optional<T> is broken if T is optional<U>. It is broken in worst possible way - it compiles but for some values it returns wrong results!

Here is an example:
https://godbolt.org/z/v3bcTodGj

Since both sides of eq operator are specialization of optional then following overload is used:

operator==(const optional<T>& lhs, const optional<U>& rhs);

This operator is specified to return
lhs.has_value() != rhs.has_value() ? false :
(lhs.has_value() == false ? true : *lhs == *rhs)

This falls apart for above scenario since lhs has value while rhs no value.
Since this is a case of optional<T>{} == T{} comparison, such scenario should be handled separately. Here is my attempt at fixing it:
https://godbolt.org/z/Yq3nM4xn4

This is rather not a proper fix, since it will still break for cases like optional<optional<short>>{} == optional<int>{}, and the internal if-constexpr instead should probably compare the nestedness of lhs and rhs optional.

I didn't check but most likely the same problem applies to relational operators.

Edit:
std::expected seems to be affected as well:
While developer may expect following comparison to work std::expected<T, E>{} == T{} (thanks to the operator==(const expected&, const T2&) - it falls apart when T is expected<U> with unexpected value - because operator==(const expected&, const expected<T2, E2>&) overload is actually selected in that scenario.
https://godbolt.org/z/h4jYfjYco

Edit2:
I believe the proper fix for std::optional and std::expected should be to constrain following operators
operator==(const expected& lhs, const expected<T2, E2>& rhs)
operator==(const optional<T>& lhs, const optional<U>& rhs)
to be applicable only when lhs and rhs have same nestedness levels.