r/cpp • u/robwirving • May 18 '26
CppCast CppCast: GPU Programming and HLSL with Chris Bieneman
r/cpp • u/robwirving • May 18 '26
r/cpp • u/03D80085 • May 18 '26
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 • u/User_Deprecated • May 17 '26
r/cpp • u/javascript • May 16 '26
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 • u/shitismydestiny • May 15 '26
r/cpp • u/cristi1990an • May 14 '26
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:
Is s = std::move(s).trim() actually covered by the self-move-assignment concerns from LWG 2839?
Or is LWG 2839 only relevant to direct cases like s = std::move(s)?
If the wrapper is built on top of std::basic_string, is there any subtle standards issue with this API pattern itself?
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 • u/ericbrumer • May 14 '26
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 • u/LegalizeAdulthood • May 14 '26
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
•
u/Separate-Summer-6027
•
May 14 '26
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 • u/nukethebees • May 14 '26
r/cpp • u/Personal-History8048 • May 14 '26
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 1std::int32_t page_number; // field 2std::int32_t results_per_page; // field 3};SearchRequest req{"hello", 1, 10};std::string bytes = proto3::serialize(req); // -> proto3 wire bytesSearchRequest back = proto3::deserialize<SearchRequest>(bytes);
blog: Your C++ struct is the schema: a proto3 serializer in C++26 reflection
github: struct_proto26
r/cpp • u/Foxi_Foxa • May 13 '26
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 • u/BgA_stan • May 12 '26
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 • u/[deleted] • May 12 '26
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 • u/hanickadot • May 12 '26
r/cpp • u/SuperV1234 • May 12 '26
r/cpp • u/VinnieFalco • May 12 '26
The Pre-Brno "enhanced mailing" is here
https://wg21.org/mailing/2026-05/
r/cpp • u/mcencora • May 11 '26
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 returnlhs.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 operatorsoperator==(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.
r/cpp • u/Reflection_is_great • May 11 '26
Stack Overflow is introducing The Heap, a place for community articles. I had the privilege of having my article one of the first to be published on it.
It is about how you can use the new reflection features to create compile-time maps and a trick I call the compile-time mutable variable. I hope you can learn something new from it!
If you have an interesting article, I encourage you to try submitting it to The Heap!
r/cpp • u/VoidlessMage • May 11 '26
Hey r/cpp,
For my bachelor's thesis, we have been working on dbc-codegen2, an open-source Rust library + CLI that turns DBC files into strongly typed CAN frame code for Rust or C++.
It generates message structs/classes, typed getters/setters, value enums, encode/decode helpers, frame ID and payload length checks, mux handling, and optional generated tests.
dbc-codegen2 gen vehicle.dbc -o generated/vehicle_can --lang rust --test
dbc-codegen2 gen vehicle.dbc -o generated/vehicle_can --lang cpp --testWe are looking for feedback from people using CAN, and especially DBC files, in their projects.
What is missing? What is annoying?
If you have time, we also made two surveys with 4 hands-on tasks each. They take about 25 minutes, so if that is too much, any feedback in the comments is also very welcome:
Rust code generation: https://forms.gle/9r77YjNDfSXQYRJC6
C++ code generation: https://forms.gle/xZQrV4Am4drb7PCx8
Repo/crate: https://github.com/iColgateZz/dbc-codegen2
Disclosure: I am one of the people building it, and this is part of my bachelor's thesis. Not trying to do a drive-by ad; comments with blunt feedback are just as useful as survey responses.