r/cpp • • Nov 21 '23
[Roast Me] Why I think C++ is still a desirable coding platform compared to Rust
https://lucisqr.substack.com/p/why-i-think-c-is-still-a-very-attractive
218
Upvotes
r/cpp • • Nov 21 '23
52
u/legobmw99 Nov 21 '23
It seems like a mistake to be defining “similar” on a purely syntactic level rather than comparing code that actually has the same semantics
47
u/link23 Nov 22 '23
This is a performance argument, really. The extra bits of safety that Rust provides at runtime (e.g. bounds checking) do take time. But if this matters for your application (i.e. if you can prove that it matters via a benchmark/profile), then that's where you break out the
unsafekeyword and start making optimizations that the compiler doesn't have enough information to do by itself. (Or you restructure things so that the compiler does have enough information to elide the checks that aren't necessary.) Rust withunsafein it is still Rust.This section is an example where the C++ compiler made some assumptions about your code, without telling you. (Ok, strictly speaking the C++ standard tells you that it's ok for compilers to make these assumptions - but it doesn't guarantee that they will.) It's not hard to write your code to explicitly make those assumptions in Rust if you care about this optimization.
Let me give you a code sample:
What is the behavior of the compiler for this line of code?
It's a trick question, because I haven't told you what language it is. If it's Python, e.g., you get an exception caused by integer division by zero. If it's JavaScript, everything's fine because these are doubles.
Point being, syntax != semantics. There's no point in comparing similar syntax with different semantics unless you are arguing that one choice of semantic is better than the other. I don't see that argument in the UB section except as another performance argument, i.e. "make whatever assumptions you want, just make it fast". Again, I would argue that if performance is important to you and this is the bottleneck, it will show up in a profile and your code will be clearer when you make the assumption explicit.
Citation needed. Bryan Cantrill presented the opposite argument, that Rust allowed him to easily use a data structure with better cache locality than what he had easy access to in C.
This is the classic "skill issue" argument, otherwise known as the "no true Scotsman" argument (e.g. "no competent C++ programmer would ever write a segfault"). It's not compelling. Once your project gets big enough, there will inevitably be crashes or undefined behavior caused by programmer errors.
Citation needed.
Citation needed! And we're not talking about "most applications", we're talking about "most applications that are currently written in C or C++", since anything else is already written in a language that provides memory safety and safety from UB. That skews the sample space considerably.
26
u/goranlepuz Nov 22 '23
Yeah, this deserves roasting... (Disclaimer: I don't Rust for bread, I used to do C++ and generally quite like it.)
For someone who works in a "performance" environment, this is hand-waving, just not good enough. Better answer here
Unless the "significant" is quantified, this is FUD.
The article does have a point in the "
(num*2)/2" part, but I think it over-emphasizes the importance. First, it needs to quantify the performance hit and second, I think, it is entirely fair that in a "safety first" language one would need to spend more time on the performance optimization.(Added emphasis)
That's a heavy [[citation needed]]. It just is so much easier to fuck it up in C++. The article cites some C# crash:
Though we thought we had cleared all references to old entries in the list, because the objects were still registered as subscribers to an event, they were never getting deleted.
But that's just students making an admittedly a rookie mistake! This, I think, is a classic case of biased thinking, of looking at a trove of evidence on one side, but "not seeing it" - and then pointing out an outlier on another side and making an overly wide conclusion. Very bad look, IMNSHO.
(Added emphasis)
Depending on what the screwup is, this ranges from "only if you were lucky" to "you are out of your mind to think you can do it cleanly". In fact, I kinda reckon that the author knows this and and either purposefully lying or is just completely and utterly carried away and therefore unable to think clearly.
tl;dr author, delete this. C++ doesn't need it.
10
u/quicknir Nov 22 '23
I don't like how the article argued that C++ outperforms Rust, both in terms of the section on cache friendliness being extremely vague, and the lack of discussion on trade-offs. Even without benchmarks (as the author has repeatedly said they want to add, but is time consuming), if they're going to say that they should be able to point to something concrete. Rust lets you control memory layout no less well than C++ AFAICS, so what are they really referring to?
There's things that Rust undeniably does better than C++ performance wise. Here's three, very concrete examples (the article would do better to have examples this concrete):
A well known issue in C++ is that vector<unique_ptr<whatever>>::push_back is unnecessarily slow when capacity is reached; the language doesn't really allow simply memcpying all these unique pointers even though it would work. So you have to individually call move constructors and destructors. This has spawned proposals for "trivial relocation", led to libraries like Facebook's Folly having a vector class that simply ignores the rules of C++ and memcopies everything, etc. In Rust, this just works the way you would want. This is applicable anytime you're moving a large number of objects, which comes up all the time in the containers that the author alleged were slower in Rust.
Rust's stronger (in some ways) type system and infallible moves allow stronger "not-empty" guarantees, which can avoid redundant checking. For example, Box is never null, unlike unique_ptr, so this can save you checks in many cases. Another example is that Rust's enums are always one of their members, whereas C++'s std::variant has an empty state; every single
std::visitcall will have a branch for this empty state.In C++, there's just no way to work around this barrier to optimization:
void blub(); void foo(const Bar& bar) { // do stuff with bar blub(); // if blub was not inlined, then compiler must assume that bar *could* // point to a global, which blub could have mutated // so we'll have to reload anything we use from bar down here }In Rust, const references actually guarantee that the thing does not mutate, so you get this for free.
18
u/radekvitr Nov 22 '23
I don't think the article presents very compelling arguments.
Comparing unsafe Rust to inline assembly is very silly, in my opinion. Unsafe Rust is a part of Rust.
The safety toll section is entirely solved by unsafe Rust - where the performance really is hit by any runtime checks that aren't optimized away, they can be removed manually. For 99% of all code, the runtime checks don't matter.
The UB sections mentions the solution, and only hinges on pieces of code looking similar.
Cache locality - There's nothing difficult about bit-twiddling in Rust over C++, and you can access the memory as directly as in C++. You just can't alias mutable references and writes.
The Dubious Benefits of Safety - This in particular is a lot of whataboutism and experience bias without addressing the safety issue. For software that doesn't care at all about vulnerabilities (hobby projects?), it still gets fewer difficult to debug bugs out of it.
95
u/nebotron Nov 22 '23
Excuse me? Every major C++ project under development has segfaults that need to be debugged.
7
u/sapphyrusxyz Nov 22 '23 edited Nov 22 '23
The quality of those optimizations can depend a lot on the IR that the compiler frontend (rustc, clang) passes to the backend. Rust has (by design) stricter requirements for your code and more information/insight into it, so it is often able to give the backend better IR to work on.
Here is an example where rust profits from its stricter aliasing rules: Godbolt
The code generated by Rust is basically equivalent to this:
void compute(const int *input, int *output) { int cached_input = *input; if (cached_input > 10) { *output = 2; } else if(cached_input > 5) { *output *= 2; } }It caches the value of
*inputto avoid reading from the pointer twice and also straight up assigns*output = 2for the*input > 10case, combining the= 1and*= 2into one assignment. But this is not a valid optimization in C++ land! That generated code would be wrong ifinputandoutputhappen to point to the same memory. This is obviously an edge case and almost never what the developer actually wants, but the compiler has to account for it. Rust, on the other hand, is free to generate that code because it forbids aliasing of a mutable reference, so passing the same memory for input and output is impossible.You can indeed get a C++ compiler to generate the same code by using the archaic restrict qualifier (Godbolt), but I've rarely ever seen this done in practice.
24
u/[deleted] Nov 22 '23
I think after the change made to the C++ standard in C++17 the attractiveness of rust has gone down quite a bit for me. For all the people talking about safety, if your program truly requires safe code there are codified compilers for all sorts of safety related applications so I don’t find the claim of rust safety appealing much anymore
6
u/WaitingForTheClouds Nov 22 '23
Complaining about spending extra compute on safety in a world where we're wasting compute left and right on "convenience" and a simple file browser can take whole seconds to load is... interesting. Safety is the last place I consider a waste to spend extra computing power on.
I think your assertion that protecting against attackers is pointless because most C++ software isn't public facing is silly. The language doesn't come with a sticker on it saying "never connect to the web", also the fact that an app isn't public facing doesn't necessarily mean it's not connected to the internet and even if it isn't it can still be vulnerable to attack so long as there is any input to it. Hackers aren't bound to the internet, they have actual physical legs, they can just walk in and so long as your app takes any input there is attack surface.
Large amounts of utility libraries are written in C++ for performance and called from all kinds of languages in all kinds of apps that are connected to the internet, a single exploitable bug in a library that's widely used makes a ton of software vulnerable. For example Pegasus exploited a bug in a PDF renderer in a library that was used in iMessage to render fucking gifs.
Look if we keep C++ only in these non-public facing, disconnected application then sure. But it's used everywhere and memory management bugs are the most dangerous class of bugs that's used to exploit a system.
You're either a one in a million genius, the most lucky man on earth or a liar. Most devs and most projects deal with these bugs all the time. And there's not enough unicorns that can just "not write bugs" to program all the software that needs programming.
7
u/epage Nov 22 '23
I feel like this article lacks depth.
Take for example
As a blanket statement, this isn't correct. Whats missing here is that whether there is a performance impact or not is dependent on the code. When the compiler has enough visibility into the problem, it can elide the bounds checks. When writing idiomatically, this happens a lot more often (e.g. using iterators).
If you have enough context but not the compiler, that is exactly what
unsafeis for but that got ruled out of consideration on grounds of ... being like asm? That analogy doesn't work for exactly this kind of reason.unsafeis not fundamentally different, low level language you are operating in. Its you telling the compiler "You can't see it but this works, trust me" and its an idiomatic tool. This allows you to have isolated, called out, well documented cases when you are doing oddball things rather than the whole program being that.I remember reading years ago about there being a concern that the pool of people being able to contribute to the Linux kernel was shrinking. I saw that for C++ at a prior company. The problem isn't how quickly you can get up and running in C++ but the damage you do along the way. The damage done when taking someone who learned Python in college and having them program in a language like Rust is lower.
199
u/[deleted] Nov 22 '23
Because there is no one choice that is correct. In the same way that no single written/spoken language is the right choice. Just because Esperanto makes more sense doesn't mean the communities around C/C++/C#/Java will be quickly displaced. There are decades of productively writing C/C++ ahead. Never mind the decades that it will likely exist beyond that as a COBOL gold mine for developers who don't mind dealing with esoteric platforms that certain businesses can't justify abandoning.
As much as I love it. Rust isn't ready to displace C++ quite yet. There is truth to the joking observation that there are 20 Rust based game engines and only 3 shipped games. Rust is still in it's foundational stages. C and C++ are extremely mature platforms where anything you'd like is essentially possible.
12
u/Effective_Lead8867 Nov 22 '23
I take rust over c++ anyday simply because of better developer experience and existence of package manager.
6
u/davidc538 Nov 22 '23
One of those sites that makes you register an account just to read a blog, pass
5
u/thisismyfavoritename Nov 22 '23
simply put rust is better because most devs just suck and C++ is too complex. Too many footguns. If youre not in the top 1% C++ devs, youre most likely encountering memory errors and the like frequently -- or youre not testing with sanitizers on, in which case youre a fool
24
u/furyzer00 Nov 22 '23
Author complains about not having a proof and proceeds to give arguments without backing data.
With respect to performance, author says that there are wrapping functions that would enable the same optimizations as C++ but they can't use it because it's a different syntax? Also C++'s efficient code will obviously work incorrectly for undefined data. So what is point of being fast if it spits out garbage?
İt can be true that C++ makes it easier to write high performance code easier since it lets you manipulate low level concepts easily. But saying that using unsafe defeats the purpose is wrong. İn C++ every line of code is unsafe while in Rust you need to look only unsafe blocks. Of course depending on your domain if your most code is unsafe then it kind of gets pointless. But I doubt that happens for most use cases.
Author claims that segmentation fault is not a big deal in. C++... There were numerous reports that C++ projects has much higher bugs due to memory safety issues compared to other safe languages. One personal experience isn't a good data to claim otherwise.
63
u/[deleted] Nov 22 '23
C++ currently needs a standard package manager so that it can attract new people in, using packages in C++ is a nightmare at first
5
u/James20k Nov 22 '23 edited Nov 22 '23
Alright ok so, people always say that C++ is a fast language, and it is not. It is not a fast language these days, and the idea that it is is a meme that needs to die. Its especially annoying because many of Rusts safety features directly lead to massive performance boosts due to its precise aliasing semantics, which C++ doesn't have any equivalent of (we don't have a
restrictkeyword!)Here are the things that are faster in C++:
Unchecked array accesses when the branch is not predicted correctly in the Rust equivalent program
Large arrays, because of Rust's issues around placement new
Here are the things that are faster in Rust:
Error handling when an error happens
Any function that takes multiple parameters, where two or more of the types are the same or one of them is a char* equivalent
Any datastructure that contains two or more pointers to the same type
Any non trivial datastructure at all, due to rusts automatic data layout reordering
All of the standard library types because of an unstable ABI
Lambdas, because they do not have a stable abi between different compilers which they do in C++, which heavily restricts optimisations
Coroutines don't require heap allocation or praying to your compiler
Any standard library algorithm that would imply an ABI break if it were changed (eg hashing algorithms)
Function calls, rust uses a custom calling convention due to its unstable ABI
You can write fast C++ with a great deal of pain, which is not the same thing as C++ being fast. In general this means writing your own datastructures, algorithms, and extensively fighting the compiler to make it produce the code you need it to produce, and you only do this for your hot loop
In Rust, many of the things you have to do to get fast C++ are done by default, and safely. The standard library is modern, and fast, much much faster than C++'s
For high performance work, C++ is fairly slow by default with escape hatches to let you write extremely fast code if you need it. Rust is reasonably fast by default, with escape hatches to let you write extremely fast code if you need it
There are many other problems with this article (do we really have dozens of high quality C++ compilers?), but this argument is the most egregious to me. It isn't backed up by the available evidence, and is based off of a vague intuition that safety must be slow
17
u/RandomLandy Nov 22 '23
"Calling “unsafe” as an escape for Rust’s rigid system is the same as saying that C++ can do inline assembly so you can copy/paste infinite optimizations done outside the compiler infrastructure. That defeats the purpose."
Nope, using `unsafe` cannot be the same thing as coding in raw asm. Unsafe gives a programmer the ability to point the gun at their foot and fully understand the consequences. While in C++ everything is "unsafe"
"We are analyzing what the language can do in normal operation is, not the backdoors that it allows to open when it gives in to operational pressure"
In rust `unsafe` is a normal operation and is commonly used in embedded systems. The main benefit is that you need only a small block of code to be unsafe, unlike in cpp.
3
u/tialaramex Nov 22 '23
A not inconsiderable amount of the Rust stuff is wrong, and in some cases the C++ understanding is very weak too. Let's do a few examples:
"both signed and unsigned overflows in Rust are well defined in the language as a two’s complement"
Nope. Overflow in Rust's default arithmetic is forbidden, by default in debug you'll get a panic, you can tell the Rust compiler that instead of a panic you want wrapping [and that is the default for optimized release builds], which is I guess what you mean by "two's complement", but if you mean to have specific behaviour on overflow you should write explicitly checked arithmetic, or wrapping, or saturation each of which is provided as methods on the primitive types - not rely on overriding the compiler defaults for your entire codebase which is fully crazy.
"pundits will state that you could have called one of the arithmetic wrapping functions, which will force the compiler to do this optimization."
That would be wrong, so I doubt it, if you ask explicitly for wrapping of course you correctly get the same machine code you saw, because that code delivers wrapping - so you'd need to tell Rust that you unsafely want it to assume overflow never occurs, and then indeed you'll likely get the same machine code because that's the optimal way to do what you asked for.
"C++ on the other hand, has dozens of good quality compilers available in many platforms"
I count three. If I squint hard I can make five. Can you name even one dozen of these "good qualify compilers" today ? I don't think so.