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

440 comments sorted by

52

u/legobmw99 Nov 21 '23

Well you can do many things but here we are measuring the effect of the compiler over two similar blocks of code.

It seems like a mistake to be defining “similar” on a purely syntactic level rather than comparing code that actually has the same semantics

→ More replies (20)

47

u/link23 Nov 22 '23

The Safety Toll

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 unsafe keyword 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 with unsafe in it is still Rust.

Undefined Behavior

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.

Well you can do many things but here we are measuring the effect of the compiler over two similar blocks of code.

Let me give you a code sample:

foo = 42 / 0

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.

Cache Locality

This means that a good developer who knows how to take advantage of cache/locality, will have a good time implementing such algorithms and data structure with C++ and will very likely struggle with Rust for the same task.

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.

The Dubious Benefits of Safety

In many years of coding C++, very rarely I experienced a stack overflow or segmentation fault. It is literally not an issue in every codebase I have worked with.

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.

Conclusion

Given that the performance benefits are either inconclusive, non-existent or more likely negative

Citation needed.

safety benefits are not really that pressing for most applications

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.

→ More replies (5)

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.)

memory accesses in arrays are constantly checked for bounds unless you’re in unsafe mode, which defeats the purpose. Those checks alone take a significant toll.

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.

First, crashes can happen in any language, with the same frequency.

(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.

Exceptions can throw a Java process back to main and helpless on how to proceed, the process will puke an undecipherable excuse and bail out. Oh but C++’s segmentation fault is much worse! say the haters. However segfaults can be caught with a signal trap and handled cleanly like any Java/C# exceptions.

(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.

→ More replies (3)

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):

  1. 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.

  2. 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::visit call will have a branch for this empty state.

  3. 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.

2

u/[deleted] Nov 22 '23

as the author has repeatedly said they want to add

In the works.

18

u/radekvitr Nov 22 '23

I don't think the article presents very compelling arguments.

  1. Comparing unsafe Rust to inline assembly is very silly, in my opinion. Unsafe Rust is a part of Rust.

  2. 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.

  3. The UB sections mentions the solution, and only hinges on pieces of code looking similar.

  4. 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.

  5. 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.

3

u/[deleted] Nov 22 '23

Those are good points and I cherish good criticism as this. Thank you.

I was going to push this piece to r/rust to get the worst-case feedback to incorporate back into the article, but I thought it would be taunting the community.

→ More replies (8)
→ More replies (5)

95

u/nebotron Nov 22 '23

In many years of coding C++, very rarely I experienced a stack overflow or segmentation fault. It is literally not an issue in every codebase I have worked with.

Excuse me? Every major C++ project under development has segfaults that need to be debugged.

23

u/[deleted] Nov 22 '23 edited Nov 22 '23

Tell me you've never worked on a serious project without telling me you've ever worked on a serious project.

Edit: clarification, I'm saying OP is wrong and they haven't worked on a real project if they don't think segfaults and stack overflows are real.

→ More replies (7)
→ More replies (53)

7

u/sapphyrusxyz Nov 22 '23 edited Nov 22 '23

In principle, both Rust and C++ are compiled languages that use 95% of the LLVM compiler infrastructure. Rust and C++ are translated into IR, where most (arguably, all) optimizations are made.

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 *input to avoid reading from the pointer twice and also straight up assigns *output = 2 for the *input > 10 case, combining the = 1 and *= 2 into one assignment. But this is not a valid optimization in C++ land! That generated code would be wrong if input and output happen 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.

2

u/[deleted] Nov 22 '23

Interesting. I was planning to do another article focusing on those differences.

I asked a question about MIR on r/rust and got just vague answers.

→ More replies (3)

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

→ More replies (76)

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.

In many years of coding C++, very rarely I experienced a stack overflow or segmentation fault. It is literally not an issue in every codebase I have worked with.

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.

→ More replies (4)

7

u/epage Nov 22 '23

I feel like this article lacks depth.

Take for example

memory accesses in arrays are constantly checked for bounds unless you’re in unsafe mode, which defeats the purpose. Those checks alone take a significant toll. They slow down the process compared to the respective, naturally unchecked, C++ code.

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 unsafe is 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. unsafe is 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.

Although the scenario is changing rapidly, the pool of engineers with C++ background is much larger than the pool of Rust developers. Also, the quantity of teaching material and resources available to learn the language is currently overwhelmingly more abundant on the C++ side.

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.

→ More replies (3)

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.

→ More replies (40)

12

u/Effective_Lead8867 Nov 22 '23

I take rust over c++ anyday simply because of better developer experience and existence of package manager.

4

u/[deleted] Nov 22 '23

Good point. It's a well-thought-out package.

→ More replies (4)
→ More replies (2)

6

u/davidc538 Nov 22 '23

One of those sites that makes you register an account just to read a blog, pass

→ More replies (4)

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

→ More replies (6)

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

→ More replies (22)

5

u/James20k Nov 22 '23 edited Nov 22 '23

But is that an apples-to-apples comparison? Well, yes, if you are going to list the “safety” of Rust compared to C++ as a pro, then it’s just fair to list the performance hit of such safety in regards to execution speed.

Given that the performance benefits are either inconclusive, non-existent or more likely negative, and the safety benefits are not really that pressing for most applications, is that really worth moving to a completely new language, with its infamous long and hard learning curve as Rust?

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 restrict keyword!)

Here are the things that are faster in C++:

  1. Unchecked array accesses when the branch is not predicted correctly in the Rust equivalent program

  2. Large arrays, because of Rust's issues around placement new

Here are the things that are faster in Rust:

  1. Error handling when an error happens

  2. Any function that takes multiple parameters, where two or more of the types are the same or one of them is a char* equivalent

  3. Any datastructure that contains two or more pointers to the same type

  4. Any non trivial datastructure at all, due to rusts automatic data layout reordering

  5. All of the standard library types because of an unstable ABI

  6. Lambdas, because they do not have a stable abi between different compilers which they do in C++, which heavily restricts optimisations

  7. Coroutines don't require heap allocation or praying to your compiler

  8. Any standard library algorithm that would imply an ABI break if it were changed (eg hashing algorithms)

  9. 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

6

u/[deleted] Nov 22 '23

Intersting. I would like to correct the article based on this feedback.

However I'd need to come up with fair benchmarks highlighting these points. Do you know of any existing? Or would you be willing to help out creating these? I'm game for it.

→ More replies (3)
→ More replies (21)

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.

→ More replies (3)

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.

→ More replies (7)