C++ - Reddit
226 subscribers
48 photos
8 videos
24.6K links
Stay up-to-date with everything C++!
Content directly fetched from the subreddit just for you.

Join our group for discussions : @programminginc

Powered by : @r_channels
Download Telegram
BEVE)

`glz::lazy_json` provides on-demand parsing with zero upfront work. Construction is O(1) — it just stores a pointer. Only the bytes you actually access get parsed.

std::string json = R"({"name":"John","age":30,"scores":[95,87,92]})";
auto result = glz::lazy_json(json);
if (result) {
auto& doc = *result;
auto name = doc["name"].get<std::string_view>(); // Only parses "name"
auto age = doc["age"].get<int64_t>(); // Only parses "age"
}

For random access into large arrays, you can build an index in O(n) and then get O(1) lookups:

auto users = doc["users"].index(); // O(n) one-time build
auto user500 = users[500]; // O(1) random access

You can also deserialize into structs directly from a lazy view:

User user{};
glz::read_json(user, doc["user"]);

# HTTP Server, REST, and WebSockets

Glaze now includes a full HTTP server with async ASIO backend, TLS support, and WebSocket connections.

# Basic server

glz::http_server server;

server.get("/hello", [](const glz::request& req, glz::response& res) {
res.body("Hello, World!");
});

server.bind("127.0.0.1", 8080).with_signals();
server.start();
server.wait_for_signal();

# Auto-generated REST endpoints using reflection

You can register C++ objects and Glaze will automatically generate REST endpoints from reflected methods:

struct UserService {
std::vector<User> getAllUsers() { return users; }
User getUserById(size_t id) { return users.at(id); }
User createUser(const User& user) { users.push_back(user); return users.back(); }
};

glz::registry<glz::opts{}, glz::REST> registry;
registry.on(userService);
server.mount("/api", registry.endpoints);

Method names are mapped to HTTP methods automatically — `get*()` becomes GET, `create*()` becomes POST, etc.

# WebSockets

auto ws_server = std::make_shared<glz::websocket_server>();

ws_server->on_message([](auto conn, std::string_view msg, glz::ws_opcode opcode) {
conn->send_text("Echo: " + std::string(msg));
});

server.websocket("/ws", ws_server);

https://redd.it/1rrq9e6
@r_cpp
I feel concerned about my AI usage.

I think use of AI affects my critical thinking skills.

Let me start with doc and conversions, when I write something it is unrefined, instead of thinking about how to write it nicer my brain shuts down, and I feel the urge to just let a model edit it.

A model usually makes it nicer, but the flow and the meaning and the emotion it contains changes.
Like everything I wrote was written by someone else in an emotional state I can't relate.

Same goes for writing code, I know the data flow, libraries use etc. But I just can't resist the urge to load the library public headers to an AI model instead of reading extremely poorly documented slop.

Writing software is usually a feedback loop, but with our fragmented and hyper individualistic world, often a LLM is the only positive source of feedback. It is very rare to find people to collaborate on something.

I really do not know what to do about it, my station and what I need to demands AI usage, otherwise I can't finish my objectives fast enough.

Like software is supposed to designed and written very slow, usually it is a very complicated affair, you have very elaborate documentation, testing, sanitisers tooling etc etc.

But somehow it is now expected that you should write a new project in a day or smth. I really feel so weird about this.


https://redd.it/1rrrh3e
@r_cpp
Triggering a silent Windows Factory Reset via C++: Reverse engineering the undocumented ResetEngine.dll

Hi r/cpp,

I wanted to share a project I've been working on. I needed a way to trigger a complete Windows factory reset (Push Button Reset) programmatically with zero UI overhead. Normally, this is done via SystemSettings.exe or WMI classes like MDM_RemoteWipe (which often require active MDM enrollment).

Instead of relying on those, I decided to interact directly with the underlying undocumented API: ResetEngine.dll.

I built a C++ tool that bypasses the standard UI and forces the system into the Windows Recovery Environment (WinRE) to format the partition.

The C++ Implementation: Since the API is undocumented, the code relies on dynamically loading the DLL (LoadLibraryW) and mapping function pointers (GetProcAddress) for the internal engine functions. The sequence looks like this:

1. ResetCreateSession: Initializes a session targeting the C: drive.
2. ResetPrepareSession: Configures the parameters. I pass scenarioType = 1 to force the "Remove Everything" wipe.
3. ResetStageOfflineBoot: Modifies the BCD to boot directly into WinRE, avoiding the need to manually configure ArmBootTrigger.
4. InitiateSystemShutdownExW: Triggers the reboot to let WinRE take over.

The tool requires SYSTEM privileges (easily tested via psexec -s) to successfully hook into the engine.

Repository: https://github.com/arielmendoza/Windows-factory-reset-tool

Disclaimer: If you compile and run this with the --force flag as SYSTEM, it WILL wipe your machine immediately with no confirmation. Please test in a VM.

I’d love to get your feedback on the code structure, the way the undocumented functions are handled, or if anyone here has explored the other scenario types exposed by this DLL.

https://redd.it/1rs2cir
@r_cpp
Modern declarative EDSL for graphic user interface in C++? Not QML or XAML.

Hello everyone,

I have been investigating lately (after using NiceGUI for a real project) and learning Jetpack Compose (not writing any real code with it, would do it with Jetpack Multiplatform if ever).

I am really impressed by Jetpack Compose approach, especially UDF.

I thought there could possibly not be a better way than MVVM tbh, after using it for years.

But after seeing how declarative composition inside the language, not with XAML or QML can be done, I am sold in the amount of boilerplate that can be saved, plus the better integration when the dsl is in the host language.

So I wanted to mention I found this, which I think could be a good start for some experiments, on top of wxWidgets: https://github.com/rmpowell77/wxUI

I think it has a talk in CppCon2025 here: https://www.youtube.com/watch?v=xu4pI72zlO4

Kudos to the author for bringing something like this to C++! Definitely useful.

I would like to hear your opinions on this style of EDSL GUI embedding and pros/cons you find for those of you who do GUI programming all the time.

Also, wild idea: with the power of compile-time C++ programming and C++26 reflection, it would be possible to get existing xaml interfaces and convert it into regular C++ at compile-time via #embed or #include and not even changing the EDSL itself and making it directly embedded and reusable in C++? That would be plenty useful.


https://redd.it/1ry51fg
@r_cpp
Made a simple neural network in C implementing Stochastic Gradient Descent algorithm

Repo: https://github.com/aadityansha06/DL-C/blob/main/stochastic-gradient-descent.c

So I mostly code in C, yesterday I thought of trying doing DL though I never did any course or something on DL, I have basic understanding of what neuron is, what forward propagation means etc... just these basic terms.
Thus I tried to create very small neural network or a single layer neuron which get trained on single dataset to find the optimal weight for it. Like if yre input is 2 and expected output is 4. Thus optimal weight i got was around 4.000002 in 300 epochs

After doing this I tried to do it for multiple dataset like {2,4} {3,9} {4,16} but I wasn't able to do. Thus I asked Ai what's the issue it said that I have implemented Stochastic Gradient Descent algorithm which work for single dataset meanwhile for multiple dataset, I needed to find the gradient for each of the dataset and the it's mean value or something and then optimizing it (today studying about gradient maths tbh on yt )..

The whole reason I'm sharing this because I never knew something like Stochastic Gradient Descent algorithm exist and unknowingly I implemented it rather getting into tutorial hell or something and learnt a lot more other stuff..






https://redd.it/1rynx7r
@r_cpp
How do you reduce branch mispredictions?

I was looking into it recently and realized how many algorithms work together in order to predict branches, so I was wondering how performance engineers even figure out what will make a certain branch more predictable

https://redd.it/1ryrjsq
@r_cpp
splice: a C++26 reflection-based hook and signal library

I’ve been experimenting with static reflection in the gcc16 trunk. I’ve built a library that lets you annotate class/struct methods and inject behavior through attributes.

You mark methods as hookable with [[=splice::hook::hookable{}]], then you can inject before/after/return hooks at runtime through a registry. You can cancel calls, override return values, rewrite arguments and control execution order by changing the priority of your hooks, all without touching the original class.

It also has a wire system for signal/slot connections. Slots declare which signal they handle via reflection attributes, and you can connect specific, or all signals on a listener. Listeners can also be paused, resumed, and they automatically disconnect when destroyed via RAII. If you want to wire a listener to for example, an on_click method on a class, you just add an attribute: [[SPLICE_WIRE_SLOT(.signal = ^^MyClass::on_click)]]

This currently requires GCC 16 (built from a snapshot) and the -freflection compiler flag. Still early, but all the tests pass and the API feels simple to use. Eventually, I want to use the same reflection machinery to generate FFI bindings for Lua, and maybe other scripting languages too.

GitHub: https://github.com/FloofyPlasma/splice

Curious if anyone else is experimenting with the reflection coming in C++ 26.

https://redd.it/1rxj838
@r_cpp
C++26: Span improvements and freestanding.

Given the freestanding remarks at https://www.sandordargo.com/blog/2026/03/18/cpp26-span-improvements blog post.

> As freestanding environments generally cannot support exceptions, parts of these facilities cannot be included. Specifically, span::at() (since it throws std::outofrange) and all overloads of std::expected::value() are excluded from the freestanding subset.

It appears that once again, even with C++26 hardening runtime, there were some security improvements that were left out of the table when targeting freestanding environments.

Like possibly having some try_at() that would return std::optional or std::expected result types.

At least looking at the proposed std::span I am not able to find such alternatives.

https://redd.it/1rwznpr
@r_cpp
What open source projects in C++ have the highest code quality?

My understanding of the characteristics of quality code are the conventional ones.

* operations on an object that are allowed in a particular object state do not put the object into an invalid state.
* it's prioritized to organize the implementation of each object into the smallest possible number of sub-objects.
* no cryptically abbreviated names are used, except possible in very small scopes.

With the program(s)/executable(s) themselves, as well as modules with corresponding namespaces, being considered singleton objects.

Fair dinkum if you want to name projects that score well under a different understanding of code quality.

https://redd.it/1rwokuj
@r_cpp
Draft idea: constructor member designators

I’ve been experimenting with a small idea to make constructor initializer lists a bit clearer and less error‑prone. The idea actually came from a dilemma I had when trying to settle on naming conventions for member variables. Prefixes like m_ or _name help avoid shadowing, but they also feel like a workaround for something the language could express more directly.

I wrote a short draft exploring “constructor member designators” - a `.member` syntax for constructor initialization.

https://github.com/richardcervinka/cpp-constructor-member-designators

This is just an experiment, but maybe someone will find it interesting.

https://redd.it/1ryyizp
@r_cpp
C++/sys - A Standard Library Projection to Facilitate the Verification of Run-time Memory Safety

Hi all,

A while ago I was looking for a relevant C++ conference to demonstrate the capabilities of C++/sys. A pure C++ mechanism which offers a new approach to memory safety via debug-time verification.

My talk was accepted into C++Online 2026 which concluded a couple of weeks ago. The discussions were great, I received some really useful feedback (and the little 2D gather town was pretty fun!).

The slides are available here and the release video should appear on YouTube in the following weeks.

Excited to share the tech with the wider community. Much of it is discussed in the slides; some highlights:

Offers improvements over AddressSanitizer in terms of C++ error detection rate
Tracks access lifespan rather than blocks of data
Has contextual knowledge of C++ objects and containers so generally quite performant
100% detection rate for executed paths
Memory pinning and locking mechanism tracks dangling 'this' and references
Zero overhead in release builds
Compatible with any standard C++ compiler (from hosted C++98 running on MS-DOS to freestanding C++${LATEST} on Zephyr)
Doesn't interfere with C code/libraries. Just like Java, Rust, Python thin-bindings, these are treated as unchecked.

Some of the above sounds like magic but the core mechanism allowing for this is quite simple. Temporaries created by operator->, operator* and operator[\] lock memory for the lifetime of access and pointers are entirely prevented from dangling in a coarse-grained manner. Obviously this has an impact on what designs are possible with some discussion in the slides.

Link to the open-source (BSD 3-clause) reference implementation is here.

https://codeberg.org/kpedersen/sys\_public

https://research.thamessoftware.co.uk/sys

Very happy to discuss further. It has some rough areas but I personally love the tech and find it makes writing and testing C++ considerably more satisfying knowing that there is virtually zero chance of a memory error lurking in the tested branches.



https://redd.it/1rz3df4
@r_cpp
A matter of style or is it?

Which one do you prefer (the constructor does some work and sets valid_):

class A {
public:
explicit operator bool() const { return valid; }

private:
bool valid_ = false;
}


or

class A {
public:
bool is_valid() const { return valid; }

private:
bool valid_ = false;
}


On the caller side:

A a{};
if (a) {
// is valid
}


or

A a{}
if (a.is_valid()) {
// is valid
}


https://redd.it/1rz8gq5
@r_cpp
Should assertions be used frequently in software development? And in what general scenarios are they typically applied?



https://redd.it/1rzfy9i
@r_cpp
Last C++26 meeting in Croydon is about to begin

Since not everyone is aware and confusion often arises regarding privated GitHub repos, let's inform people on Reddit this time: The last meeting for C++26 is about to begin. Some quick facts:

- The meeting lasts from 2026-03-23 (Mon morning) to 2026-03-28 (Sat afternoon). See also <https://isocpp.org/std/meetings-and-participation/upcoming-meetings>
- Until the meeting ends, <https://github.com/cplusplus/papers/> is private. The repos usually become visible again immediately after the meeting ends.
- The papers published during and after the meeting all go into the April mailing 2026-04-20. This includes the final working draft.
- All remaining NB (national body) comments should be resolved during this meeting. The working draft is then sent off to ISO for review and national bodies vote on the C++26 standard as a whole (yes/no/abstain).
- Any C++26 work takes priority, but once that is completed, time is spent on C++29 papers.

https://redd.it/1rzjovp
@r_cpp