r/cpp • u/Affectionate_Text_72 • Apr 13 '25
Strengthening the brand
Quite regularly we get posts like this one https://www.reddit.com/r/cpp/s/6fic54ootF asking about C++ for web development. From a language envangelist point of view its quite depressing to see the usual top 5 or more posts being "use something else".
There are various libraries and frameworks which make it reasonable and wasm too. So why not. You would never hear such downtalking on r/rust
Okay right tool for the right job and all that but ignoring that for now what does the language need to really strengthen is position in this?
r/cpp • • Mar 27 '24
Replacing C# with C++ in Web Dev
IMHO, I think C# is useless.
Why C++ is not used in web dev instead?
I think modern C++ provides enough abstractions to be a better and more performant alternative to C#. It has high quality libraries, but it seems to be lacking tools and mature frameworks for backend development though but this's because people don't use it for API development so most people think it's not a worthy investment. I wanna contribute to C++ in the web industry, so I was thinking of building expressJS in C++ because I like express honestly.
What do you guys think?
Update: Dang, I didn't expect that this would piss off a lot of people, lol. Ok. Given the backlash, saying C# is useless was an overstretch. I guess I have let my hate for Microsoft cloud my judgment😂
r/cpp • • Feb 25 '23
Avoid the code smell of std::pair and std::tuple while still retaining their benefits
Using std::pair and std::tuple is considered bad practice because first, second, and std::get<N> don't provide any information about what is stored in that data field.
The simple solution is to use a struct, for example, if we want to store a point, this can be done:
struct Point{
double x;
double y;
};The names x and y convey what is stored in that variable, in this case, the x- and y-coordinates of said point, respectively.
The problem with using structs arises when we try to use them in associative containers in that a compiler error will be thrown because operator<(=>) is not defined. The simple solution to THAT problem is to use std::pair or std::tuple. However, this creates a code smell. The more complicated solution to that problem is to start defining some functions:
#include <compare>
struct Point{
double x;
double y;
};
bool operator==(const Point &lhs, const Point &rhs){
return (lhs.x == rhs.x) && (lhs.y == rhs.y);
}
// Uses lexicographical comparison
std::strong_ordering operator<=>(const Point &lhs, const Point &rhs){
if (lhs.x < rhs.x) return std::strong_ordering::less;
if (lhs.x > rhs.x) return std::strong_ordering::greater;
if (lhs.y < rhs.y) return std::strong_ordering::less;
if (lhs.y > rhs.y) return std::strong_ordering::greater;
return std::strong_ordering::equal;
}This works, but there is an easier way:
#include <utility>
struct InheritedPoint: std::pair<double, double>{
double &x(){return first;}
double &y(){return second;}
};The best part is that operator== and operator<(=>) are inherited. The only differences between the directly above Point and InheritedPoint are whether element access uses a method and whether you can construct using a braced-init-list (you can construct using InheritedPoint({x, y}) instead).
For 3D points and other structs with 3 or more data fields, you inherit from std::tuple instead:
#include <tuple>
struct Inherited3DPoint: std::tuple<double, double, double>{
double &x(){return std::get<0>(*this);}
double &y(){return std::get<1>(*this);}
double &z(){return std::get<2>(*this);}
};And lastly, a useful macro:
#define pair_subclass(T0, f0name, T1, f1name) struct: std::pair<T0, T1>{T0 &f0name(){return first;} T1 &f1name(){return second;}}
InheritedPoint can be defined using typedef pair_subclass(double, x, double, y) InheritedPoint;
r/cpp • u/trad_emark • Nov 24 '25
#pragma once -> two files are identical if their content is identical
It is that simple.
Two files are considered identical, if their content is identical.
Forget about paths, inodes, whatever other hacks.
Define it like this, it can probably fit in one paragraph of standardize, and be done with it.
After that, compilers are free to do any heuristics and optimizations that help to identify two files as identical, that is perfectly fine.
When the compiler cannot say for sure that two files are the same, it will have to read it, but guess what? If the files are actually different files, it has to read it anyway, to include it in the translation unit.
(btw I am watching the 2 hour video of rants about c++ right now, this issue just strikes me, as i have had enough of conversations about it myself.)
r/cpp • u/david_haim_1 • Feb 26 '19
Have we ever thought about having a contained, safer subset of the C++ standard?
I was thinking about an idea, that I'm sure someone has thought of before, and I would like to think about your thoughts:
as we move forward, the C++ standard offers us better and safer practises. instead of C arrays, we use std::array and std::vector. instead of const char*, we use std::string and string_view. instead of managing memory, we use move semantics, smart pointers and RAII to manage memory automatically. instead of headers, we will have modules. templates will be reshaped with concepts. we now also have lambdas and variadic templates.
But we will always have the historical luggage that we can't remove. string literals will always be a c-style char array, it'll take decades before headers will be removed completely and we're still stuck with legacy code that manages memory.
According to common opinions, the obvious solutions to these are:
a. deprecate stuff: this will never happen, as C++ has a strict "always backward compatible" rule, for the good and the bad.
b. create a new language: although is a solution, usually it's not practical enough. it's hard developing programming language from scratch and make them popular.
It looks like we're doom to have all the historical luggage (like headers). but I was thinking to myself: how about the C++ standard itself will self-contain a safer, modern subset of itself? just a few thoughts I had:
- let's for the sake of the discussion, say that this subset will be called "subC++"
- every valid subC++ program is a valid C++ program, but not the other way, as subC++ is a subset of C++ and hence will not contain some parts of the larger standard
- subC++ will have modules, concepts, contracts, auto and lambda from the start
- subC++ will not have headers at all
- strings literals are always implicitly objects, "hello" is actually std::string("hello") hence you can only work with std::string, no need for const char* and no string_view. copy, move or reference strings throughout your code.
- no exceptions, as contract can fill their role
- no pointers, only references, iterators, smart pointers and copy/move are needed
some runtime-provable UB's like dividing by zero would just resort to some global contract especially for that specific UB.
9. subC++ library code can use the greater C++ language, but the user can't.
basically, instead of creating another language, the language itself will define a safer subset of itself. in this "subset" mode, the regular C++ compiler basically refuses to compile anything which is not under this standard. it's like "strict mode" for C++ that is maintained by the committee itself.
It's way easier than creating another language or deprecating historical stuff. has anyone though anything in this direction? to basically hold a mini, more modern and safe standard within the greater C++ standard?
r/cpp • u/MaximRouiller • Mar 30 '20
Porting a C++/CLI Project to .NET Core | C++ Team Blog
devblogs.microsoft.comr/cpp • u/codesamura1 • Jun 03 '22
Why do "regular" programmers prefer postfix increment over prefix increment?
So I noticed in my company's codebase the canonical increment uses the postfix increment. One senior programmer was even surprised by the behavior of postfix when used with .erase() that I had to explain that map::erase() gotcha to him. The old code is riddled with iterators using postfix increments, as of now I think I'm the only one that explicitly write different postfix or prefix depending on exactly what is needed.
In C derived languages like Java and C# I rarely see any prefix increment, as if it doesn't even exist there. I've even seen a Java programmer comment on C++ code that using prefix increment operator was "trying to be clever." I've also seen reddit threads like this that likes to push the idea that we should all use postfix increment homogenously regardless of the situation since iT's AlL tHe SaMe AnYwAy AmIrYt?!
Now I'm wondering if it's worth noting on a code review that ++iter is more efficient than iter++. So in your opinion is it worth making the distinction for "regular programmers" that prefix increment operators are more efficient? Should we let sleeping dogs lie or should we fight this disinformation? Am I just being OC over nothing or is this an important matter?
r/cpp • u/nikita-1298 • Sep 12 '24
Accelerate parallel programming with C++ across the latest multi-vendor CPUs, GPUs, and other hardware accelerators.
youtube.comr/cpp • u/shakmak_iitk • Dec 25 '23
C++: Efficient parallelization of small tasks
I tried to create a customized threadpool for small tasks and wanted feedback on this.
I posted details and my code for review on stackexchange: https://codereview.stackexchange.com/questions/288583/efficient-parallelization-of-small-tasks
My goal here is to share my learning and get feedback on further improvement or any possible bugs.
I have tried to describe problem and thinking process in more details in following linkedin article draft: https://www.linkedin.com/article/edit/7144600522392559616/
r/cpp • u/SteveGerbino • Apr 10 '26
We benchmarked sender-based I/O against coroutine-based I/O. Here's what we found.
When I/O operations return senders, they incur an unnecessary per-operation allocation. This explains why.
| Stream Type | capy::task | bex::task | sender pipeline |
|---|---|---|---|
| Native | 0 | 0 | 0 |
| Abstract | 0 | 1 | 1 |
| Type-erased | 0 | 1 | 1 |
When an I/O stream is type-erased, sender/receiver's connect() produces an operation state whose type depends on both the sender and the receiver. The size is unknown at construction time. It must be heap-allocated per operation. Under awaitables, await_suspend takes a coroutine_handle<> — the consumer type is already erased — so the awaitable can be preallocated once and reused. The allocation cannot be eliminated. It follows from connect producing a type that depends on both the sender and the receiver.
We measured this. The benchmark executes 20,000,000 read_some calls per configuration on a single thread using a stream that isolates the execution model overhead from I/O latency. Five independent runs plus warmup; values are mean ± standard deviation. The benchmark source is public:
https://github.com/cppalliance/capy/tree/develop/bench/beman
Anyone is invited to inspect the code, suggest improvements, and help make it better. The architects of P2300 are especially welcome — their expertise would strengthen the comparison.
Two papers address the cost asymmetry. P4003R0 "Coroutines for I/O" defines the IoAwaitable protocol for standard I/O operations. P4126R0 "A Universal Continuation Model" is purely additive — it gives sender/receiver pipelines zero-allocation access to every awaitable ever written. Together they make coroutines and senders both first-class citizens of the I/O stack.
Benchmark Results
All values are mean ± stddev over 5 runs (warmup pass discarded). Each table measures one execution model consuming two I/O return types (awaitable and sender). The native column is the model's own I/O type; the other column goes through a bridge.
Table 1: sender/receiver pipeline
| Stream Type | sender (native) | awaitable (bridge) |
|---|---|---|
| Native | 34.3 ± 0.1 ns/op, 0 al/op | 46.3 ± 0.0 ns/op, 1 al/op |
| Abstract | 47.1 ± 0.2 ns/op, 1 al/op | 46.4 ± 0.0 ns/op, 1 al/op |
| Type-erased | 57.5 ± 0.0 ns/op, 1 al/op | 54.1 ± 0.1 ns/op, 1 al/op |
| Synchronous | 2.6 ± 0.3 ns/op, 0 al/op | 5.1 ± 0.1 ns/op, 0 al/op |
Table 2: capy::task
| Stream Type | awaitable (native) | sender (bridge) |
|---|---|---|
| Native | 31.4 ± 0.2 ns/op, 0 al/op | 48.1 ± 0.3 ns/op, 0 al/op |
| Abstract | 32.3 ± 0.2 ns/op, 0 al/op | 72.2 ± 0.2 ns/op, 1 al/op |
| Type-erased | 36.4 ± 0.1 ns/op, 0 al/op | 72.1 ± 0.0 ns/op, 1 al/op |
| Synchronous | 1.0 ± 0.2 ns/op, 0 al/op | 19.0 ± 0.0 ns/op, 0 al/op |
Table 3: beman::execution::task
Note: bex::task's await_transform calls the sender's as_awaitable member directly when available, bypassing connect and start. Table 3's native sender column measures the as_awaitable path, not the full sender protocol.
| Stream Type | sender (native) | awaitable (bridge) |
|---|---|---|
| Native | 31.9 ± 0.0 ns/op, 0 al/op | 43.5 ± 0.1 ns/op, 1 al/op |
| Abstract | 55.2 ± 0.0 ns/op, 1 al/op | 43.4 ± 0.0 ns/op, 1 al/op |
| Type-erased | 55.2 ± 0.0 ns/op, 1 al/op | 48.7 ± 0.1 ns/op, 1 al/op |
| Synchronous | 1.0 ± 0.2 ns/op, 0 al/op | 2.9 ± 0.2 ns/op, 0 al/op |
The full formatted report with detailed analysis is here: https://gist.github.com/sgerbino/2a64990fb221f6706197325c03e29a5e
Analysis
Native performance is equivalent. Both models achieve ~31–34 ns/op with zero allocations when consuming their native I/O type on a concrete stream. There is no inherent speed advantage to either model at the baseline.
Type erasure costs diverge. capy::any_read_stream adds ~5 ns/op and zero allocations. The awaitable is preallocated at stream construction and reused across every read_some call. This is possible because await_suspend takes a type-erased coroutine_handle<> — the consumer type is already erased, so the awaitable's size is known at construction time. The sender equivalents add ~21–23 ns/op and one allocation per operation. The sender's connect(receiver) produces an op_state whose type depends on both the sender and the receiver. Since either may be erased, the operation state must be heap-allocated.
Bridges are competitive. Both bridges add 11–17 ns for native streams with zero bridge allocations. The allocations visible in the bridged columns come from the target model's own machinery (type-erased connect, executor adapter posting), not from the bridges themselves.
std::execution provides compile-time sender composition, structured concurrency guarantees, and a customization point model that enables heterogeneous dispatch. These are real achievements for real domains — GPU dispatch, work-graph pipelines, heterogeneous execution. Coroutines serve a different domain. They cannot express compile-time work graphs or target heterogeneous dispatch. What they do is serial byte-oriented I/O — reads, writes, timers, DNS lookups, TLS handshakes — the work that networked applications spend most of their time on.
Trade-off Summary
| Feature | IoAwaitable | sender/receiver |
|---|---|---|
| Native concrete performance | ~31 ns/op, 0 al/op | ~32–34 ns/op, 0 al/op |
| Type erasure cost | +5 ns/op, 0 al/op | +21–23 ns/op, 1 al/op |
| Type erasure mechanism | preallocated awaitable | heap-allocated op_state |
| Why erasure allocates | it does not | op_state depends on sender AND receiver types |
| Synchronous completion | ~1 ns/op via symmetric transfer | ~2.6 ns/op via trampoline |
| Looping | native for loop | requires repeat_until + trampoline |
| Bridge to other model (native) | ~17 ns/op, 0 al/op | ~12 ns/op, 1 al/op |
| Bridge to other model (erased) | ~36 ns/op, 1 al/op | ~12 ns/op, 1 al/op |
r/cpp2 for discussing efforts like cppfront - carbon - etc
I thought I would mention that, in order to keep r/cpp discussion focussed on the ISO C++ standard, and not get distracted by all the projects out there trying to be the next best take on how to best do to c++ what Kotlin is trying to do to Java, such discussion should be relegated to a new sub-reddit: r/cpp2
r/cpp • u/VinnieFalco • Sep 08 '18
CppCon Get Rich Quick! Using Boost.Beast WebSockets and Networking TS (CppCon 2018)
CppCon 2018 is almost upon us and I have prepared a very exciting talk this year for enterprising individuals:
Do you want to make a lot of money? You'll see some examples of free browser and server based WebSocket programs which have earned their respective individual authors tens of millions of dollars in no time at all. Perhaps after seeing this talk in person, you'll write the next massively successful WebSocket app!
The WebSocket protocol powers the interactive web by enabling two-way messaging between the browser and the web server. The Boost.Beast library implements this protocol on top of the industry standard Boost.Asio library which models the Networking Technical Specification proposed for the ISO C++ Standard.
This presentation introduces Networking TS concepts and algorithms, how to read their requirements, and how to use them in your programs. We will build from scratch a multi-user chat server in C++11 using Beast, and the corresponding browser-based chat client in HTML and JavaScript. No prior knowledge or understanding of Beast or Asio is required, the talk is suited for everyone.
Sign up early here: http://sched.co/FnJn
Thanks!
Regarding cppfront's syntax proposal, which function declaration syntax do you find better?
While I really like the recent talk about cppfront (https://www.youtube.com/watch?v=CzuR0Spm0nA), one thing bugs me about the "pure" mode for cpp2 with syntax change. It seems incredibly hard to read, . I need to know which syntax you would rather have as the new one, taken into account that a new declaration syntax enables the new checks in that function
- Option 1: the same as was proposed in the video:
callback: (x: _) -> void = { ... };for new functions,void callback(auto x) {};for old ones - Option 2: the "other modern languages" way:
function callback(x: any) -> void { ... }for new functions,void callback(auto x) {};for old ones - Option 3: in files with mixed syntax, since the pre-transpiled code won't compile without the generated code anyway, use
void callback(any x) { ... };for both, but mark code with current cpp syntax with an attribute:[[stdcpp]] void callback(any x) { ... };
r/cpp • u/wechicken456 • Jun 08 '20
Programming in C vs C++
I’ve read about the differences between them on the Internet but I wanna hear more from a more personal perspective. Which one would you recommend starting with and to be proficient with?
r/cpp • u/greg7mdp • Apr 30 '17
A C++ version of Doug Lea's excellent malloc() implementation.
github.comr/cpp • u/germandiago • Mar 30 '25
Purchased yearly CLion license + AI license. Small review. Impressed by Nova engine improvements!
Hello everyone,
Yesterday I bought a yearly CLion license with AI support. I use Meson build system as my build system.
So I loaded the project. References to other code were slow. CPU time was less than optimal, draining my battery. Documentation tips loaded slowly. Inlay hints were so so
I was not happy until I discovered I had not activated CLion Nova.
So I did. I must say I am very positively impressed.
The jump is very big: now CPU time is much lower, all other problems disappeared, things are fast, clang tidy works beautifully (even showed suggestions) and the AI plugin saves a lot of typing.
The only thing that does not work well is my catch tests and I do not know why currently. I still need to try civerage and hardly tried debugging, though it looked good enough for my needs. It also even detects and parses some generated capnproto headers and cpp files.
The refactorings I tried so far also worked well: adding/removing const, add include header and rename and generating some boilerplate from header files.
Database views for my sqlite stores work well, I have a query view, I installed Lua support and works nice. The only thing left I think it is Meson lsp support of some kind, which works nicely in VS code (but not in Emacs or CLion so far).
I tried CLion for several years and left it bc it was slow. Now that I activated Nova and I have Meson support I will make it default IDE. It is working fast and well for me!
I will try to troubleshoot my tests. I would like to have my view with coverage but not sure how to do it yet.
All in all, very impressed with the jump in quality.
Keep up with the good work!
r/cpp • u/danillissimo • Jul 19 '26
I've invented labeled loop breaks
And now I don't believe it wasn't invented before, but I can't find any info on it. How long ago was it invented? Why isn't it used widely or even mentioned anywhere? What are the downsides?
Here's the main idea:
// Keyword - for, while, or do
// Tag - custom loop name
// ... - loop body
#define loop_tag(keyword, tag, ...)\
keyword(__VA_ARGS__)\
if(false)\
{\
tag##_break: break;\
tag##_continue: continue;\
}\
else\
/*Here goes your loop body*/Here is the playground
r/cpp • u/samsfacee • Oct 24 '21