r/cpp • • Sep 04 '23

Considering C++ over Rust.

Similar thread on r/rust

To give a brief intro, I have worked with both Rust and C++. Rust mainly for web servers plus CLI tools, and C++ for game development (Unreal Engine) and writing UE plugins.

Recently one of my friend, who's a Javascript dev said to me in a conversation, "why are you using C++, it's bad and Rust fixes all the issues C++ has". That's one of the major slogan Rust community has been using. And to be fair, that's none of the reasons I started using Rust for - it was the ease of using a standard package manager, cargo. One more reason being the creator of Node saying "I won't ever start a new C++ project again in my life" on his talk about Deno (the Node.js successor written in Rust)

On the other hand, I've been working with C++ for years, heavily with Unreal Engine, and I have never in my life faced an issue that usually the rust community lists. There are smart pointers, and I feel like modern C++ fixes a lot of issues that are being addressed as weak points of C++. I think, it mainly depends on what kind of programmer you are, and how experienced you are in it.

I wanted to ask the people at r/cpp, what is your take on this? Did you try Rust? What's the reason you still prefer using C++ over rust. Or did you eventually move away from C++?

Kind of curious.

355 Upvotes

434 comments sorted by

222

u/nihilistic_ant Sep 04 '23 edited Sep 04 '23

For a long time, Java was going to kill C++. Sun wrote an operating system in it and Netscape ported their browser. Much later, I remember a period when Go was going to kill C++, which in hindsight never made a much sense as it seemed at the time. Besides these big ones, there have been plenty of other languages that were popular enough I got questions why projects were in C++ rather than them given they were hot thing, including stuff like D or Scala that are largely forgotten now but for awhile had a lot of mindshare.

Maybe Rust will actually do it. Maybe Zig will. Maybe something that will be started in a couple years will. It is hard to tell.

In general, I don't envy the programmers that are always chasing the latest language and framework. (It was particularly rough a few years ago for them, when they all ended up learning something like 6 javascript frameworks in just a few years to keep up with fads.) Their code ends up being hard to maintain, because there ends up being various systems written in different languages or frameworks that didn't stay in fashion.

Anyway, I'll be happy to move to Rust or Zig or whatever if it really does eat the world. But for myself, it makes sense to wait a few more years to see if it really does.

An issue of new languages like Rust, is their users are all programmers who decided to use the latest coolest language. That means if something new comes out, their users are the sort of people who will jump ship to that. Folks still programming in C++ have chosen not to jump ship many times before, so I'm pretty sure the language will be at least fairly popular for a long time.

33

u/isht_0x37 Sep 04 '23

I like the insight. Thank you

48

u/[deleted] Sep 05 '23

Let's not forget C++ killing C, for context on language homicide.

62

u/UnicycleBloke Sep 05 '23

That has been one of the most depressing aspects of my career as an embedded dev: the persistent myths, prejudice, denial and nonsense that keep C as the gold standard. Using C++ made me far more productive and have far fewer errors but, even after 16 years, many of my colleagues continued to repeat the same self-defeating drivel. Not one colleague who actually tried C++ went back to C unless there was no choice.

→ More replies (13)
→ More replies (1)

32

u/coderman93 Sep 05 '23

To play devils advocate though, when I evaluate knew frameworks and languages I always try to understand what actual problem they are solving. In the case of Rust, the answer is obvious and compelling. The language indisputably solves issues in a way that no other language ever has. There are a grand total of zero other languages that guarantee memory safety and thread safety at native performance.

6

u/duneroadrunner Sep 06 '23 edited Sep 06 '23

There are a grand total of zero other languages that guarantee memory safety and thread safety at native performance.

Well, in some sense I don't consider this to be true anymore. In an effort to implement an enforced safe subset of C++, I've come up with a "usable proof-of-concept" implementation of a safe subset that I'd argue rivals Rust in overall performance, while at the same time providing a wider range of performance-flexibility-simplicity tradeoff choices.

Rust relies on some compromises to achieve its safety. For example, copying the value of an (arbitrary) element in a container, like say, an array, to another element in the same container effectively requires instantiation of slices (if the container supports slices), which in practice results in the overhead of an extra bounds check. This kind of operation is sometimes unavoidable inside performance critical inner loops.

The safe subset of C++ does not incur this extra overhead. It does, for example, incur additional run-time overhead when performing operations (like insertion, removal, etc.) on dynamic (i.e. resizable) containers that could change the size/structure/location of the contents of the container. But these operations tend to be avoided inside hot inner loops anyway, as those operations can be costly even without any extra overhead.

The compromises Rust relies on also prevent support for move constructors. I think this has significant if not obvious implications on "expressiveness". Probably the most well-known being the limitations with respect to self/cyclic references. The safe subset of C++ does support move constructors (and as a result has fewer limitations with respect to self/cyclic references).

Now in practice Rust may remain unrivaled in terms of safety and performance for some time. But if so, it wouldn't be for technical reasons or due to some language design advantage. And Rust adopts compromises and limitations that are demonstrably not required to achieve similar levels of performance and safety. So in my estimation Rust leaves room for potential competitors. And it's conceivable that C++ or a derivative of C++ might be one of them. I do think that it would be a significant challenge for any competitors to match the impressive execution of Rust's development though.

To be clear, given the trade-offs Rust has chosen, I think the language design is quite optimal. I'm suggesting that those trade-offs are not ideal for many applications, and that other potential languages (including potentially C++) could provide the programmer with more flexibility in choosing different trade-offs for different situations.

→ More replies (3)
→ More replies (1)

18

u/jsadusk Sep 05 '23

So, I say this as a C++ dev for a couple decades that is now using Rust, the transition is different. People arguing that Java/D/Scala/Go/whatever will replace C++ were really arguing that higher level programming with memory management will replace the need for low level programming. And, in many domains they did, there's no need to use C++ to write a web app server most of the time. But the core need for C++, to do performance critical work that directly manages memory but still provides strong abstractions continued to exist.

Rust isn't a higher level language, its not garbage collected, it doesn't have a runtime. In theory you could transpile rust to C++, they operate on the same concepts. Rust solves one very real issue with C++, memory safety and protection against undefined behavior. The number of vulnerabilities attributable to this (arguable) flaw in C and C++ is staggering. So, rust fixes it. With the main trade off being that certain dev patters are harder to express, notably self referential datastructures.

The point is, unlike your other examples, anything that can be done in C++ can also be done in Rust. Its not a replacement in the sense that everyone is going to start using it, its a replacement in that it solves the same need as C++. And it could be arguable that it does it better. Better is subjective, so take with a grain of salt.

→ More replies (1)

17

u/HeroicKatora Sep 05 '23 edited Sep 05 '23

But Java did eat the world. At least judging by the number of FinTech jobs outside of low-latency systems, more specifically anything with JVM including Graal in the DB etc. Those fields also have full-stack Javascript (remember JS has made it to the moon!) or Python but finding C++ is almost the exception. Automotive and Computer Vision seem to be more solidified with C++, I wonder how much that is due to codependencies with CUDA that would vanish completely if AMD ever decides to seriously invest in libraries and tooling.

On that note, imo the number of recent talks on HFT in cppcon and other conferences are, in essence, post-mortems. No seriously competitive company would let anyone give those talks if the knowledge were still an advantage for the near and midterm future. C++ shines in latency-sensitive systems at best but those are getting gobbled up by ASIC's, photonic compute, and what have you, and is not and won't have been an exclusive C++ domain. If you want to do hardware-offloaded eBPF on your NIC, then good luck targetting this with a C++ compiler. But you'll readily find both C and Rust. Similarly emscripten for C++ to target barebones wasm, without environment support, is still bad after years and it does not provide the js-sys bindings either. I'm not sure why it would be hard to implement (only) bindings to the more standardized APIs but apparently, it is. And that seems to be a problem with the language that Rust doesn't have. Go figure why the HAL embeded support is so comprehensive in Rust despite its relative immaturity.

It shouldn't take a "killed" language to move, either. Otherwise you effectively end up in something like COBOL which has never been and is not dead. It's no choice for new projects and jobs in it are pure maintenance hell, though, which isn't what I want my career to end up being. "How fast is a language integrated by new architectures" is maybe a much better question to compare programming languages than measuring their LoC, project count or anything else with legacy bias.

I don't think your comment provides reasonable evidence. If anything, it gives examples that corroborate your gut feeling being faulty and then gives a gut feeling on Rust and Zig. What supports the assumption it would be correct in this instance?

6

u/oriolid Sep 05 '23

the number of FinTech jobs outside of low-latency systems

...is pretty small subset of all programming jobs out there.

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

35

u/Dean_Roddey Sep 04 '23

I think your final paragraph is quite incorrect. I would argue that a large percentage of the folks who have moved to Rust have done so for reasons that are entirely pragmatic. I've been doing C++ for right at 35 years, and never followed a fad in my professional career (unless you consider C++ a fad, since I was one of those pushing it back in the day.) My pushing for C++ back then was pragmatic, and my move to Rust now is for those same pragmatic reasons. I think many others are the same.

27

u/nihilistic_ant Sep 04 '23 edited Sep 04 '23

I have no doubt your decision was pragmatic. But your pragmatic computation of "does it make sense to switch to Rust" weighs certain factors different than those of us who have stayed, factors such as: keeping compatibility with the large prior ecosystem, the hassle of switching languages, the cost of a codebases using multiple languages, etc. Factors that will make you more likely to switch languages again.

The people were pragmatic who switched from C++ to Java, Go, Haskell, and so forth. As are the people who are switching now to Rust. As are the people who stayed with C++ then, as are those staying with C++ now. We're all being pragmatic.

Imagine that in a few years EvenBetterLang comes out, keeping all that is good about Rust but making some real improvements that will be hard to quickly add to Rust because of backwards compatibility. Will you move to it? It seems likely to me, because you made essentially the same computation when you moved to Rust. It will be pragmatic.

→ More replies (2)

12

u/c_glib Sep 05 '23

Thing is, java and go have indeed taken away projects (indeed, entire fields of programming) from C++. I have been around long enough that C++ and things like MFC were the standard way of writing enterprise apps and C++ (or indeed, plain C) was the standard choice to write a high performance concurrent server (remember pthreads?). Java and Go have taken away a large chunk of that space from C++. And for some very good, practical reasons. Rust will take away some more. In the end, C++ will turn into a niche language for niche and legacy projects. Now, the legacy part is indeed massive and there will always be projects and jobs for the practitioners. So there's no need to panic. But it's definitely hard to make the case that the space for C++ has not shrunk because of competing ecosystems.

→ More replies (3)
→ More replies (2)

77

u/UnicycleBloke Sep 04 '23

I read a couple of Rust books and spent some time on a couple of projects to see what all the hullabaloo was about. It certainly has some interesting features but I just didn't find it compelling overall. I very rarely suffer with the issues the borrow checker prevents and, to be honest, I found it overly restrictive. And I recall that I could not do something with generics at compile time that would be trivial in C++.

I liked the easy package management but felt unhappy when half the internet was downloaded in the form of a bazillion crates of unknown quality/provenance just to build a modest application. That is anathema to me. My projects mostly use the standard library and little else: a small set of libraries.

I don't think I would ever achieve the day to day familiarity that I have from three decades of C++, and my skills are in demand, so I have walked away. Were I just starting out, I would probably use Rust more and have both C++ and Rust in my skill set.

I can understand Rust's appeal to C devs and those who write C++ as if it is 1990. More modern C++ devs not so much. As an embedded developer I confess I found it irritating that some of the same C devs who have been in denial about C++ for decades now rave about Rust. Bah! Humbug!

On the other hand, I will say that I'm increasingly concerned at the growing size and complexity of C++ with each new standard. It feels like a neverending treadmill of trying but failing to keep up. Of course, Rust is less mature and also growing fast... I wonder how long it'll be before that becomes an issue. :)

38

u/isht_0x37 Sep 04 '23

I found it irritating that some of the same C devs who have been in denial about C++ for decades now rave about Rust

Exactly. Even Linus Torvalds. They never seem to appreciate what C++ brings on the table.

49

u/link23 Sep 04 '23

The problem is that in addition to the nice parts, C++ brings a lot of baggage and warts to the table.

36

u/qalmakka Sep 05 '23 edited Sep 05 '23

The problem I have with C++, as a long time embedded developer first and now game dev, is that it's too easy to inadvertently do stuff implicitly, which is potentially lethal for performance and/or safety. Implicit copy constructors and type conversions IMHO are a design blunder almost in the same ballpark as gets() - it's very easy to inadvertently trigger a deep copy of a data structure, and it takes a lot of effort and good practices to avoid that.

Implicit references are also another incredibly problematic part of C++, full of obscure and arcane decay rules and crazy stuff like const T& binding to temporaries.

Even the most seasoned of C++ developers does stuff like this all the time:

#include <iostream>
#include <unordered_map>

int main() {
    const std::unordered_map<const char*, int> m { {"a", 2}, {"b", 4} };

    for (const std::pair<const char*, int> &p : m) {
        std::cout << p.first << ' ' << p.second << '\n';
    }

    return 0;
}

without realizing that by writing std::pair<const char*, int> instead of std::pair<const char* const, int> C++ is deep copying every single value in the map in order to create a pair with a mutable key, only to then bind it to a constant lvalue reference.

Rust avoids lots of these pitfalls by making almost everything explicit, so I see why the "purist" C crowd prefers it over C++.

→ More replies (11)
→ More replies (20)
→ More replies (1)

48

u/KingAggressive1498 Sep 04 '23

Probably 90% of the issues Rust fixes are caused by not following C++ best practices to begin with. I'm talking "C with classes" style code, not using smart pointers, not using STL-style iterators, etc.

There's still that other 10% that's very much valid, which is mostly lifetime management issues. Using an STL-style iterator after its been invalidated is actually pretty easy to do and not catch for months or even years, because it doesn't cause an error until it does. Use after-free caused by dangling pointers and references will still happen in complex enough codebases even if you're using smart pointers.

If rust had stuck with full C syntax, I'd have probably tried it at least. I quite liked D for this reason, but it just never had the community that Rust now seems to, so I never stuck with that. I just find Rust code... harder to look at, to put it nicely.

27

u/isht_0x37 Sep 04 '23

I just find Rust code... harder to look at, to put it nicely.

This. Especially if you're trying to understand a specific crate like Axum or Serde, it's a pain to know what the trait bounds are, and why are they required in that particular function.

5

u/IceSentry Sep 05 '23

The thing about rust is that it's mostly just enforcing a lot of the best practices at the compiler level and then wraps it in a subjectively nice package. What I like about rust isn't even the borrow checker at this point, I just prefer the syntax and the stricter enforcement of more rules including a standardized automated formatter, a standardized build and testing framework, pattern matching and sum types.

Modern cpp with tools set up by an experienced dev can get very close to this but the issue for me is that it's not standardized in the entire ecosystem. With rust I can just clone a repo and start working almost immediately. With cpp the first step is always to look for a build guide and figure out which combination of tools this particular project uses, it often also involves figuring out if it works on windows which is less of an issue in rust projects in my experience. I like to jump around a lot and contribute to open source projects so this is an important issue for me. Just last week I tried to clone a cpp repo and run it but a dependency that was a git submodule just didn't compile. Once I finally figured out the issue I had to figure out a custom build script that only worked in visual studio and I gave up at that point.

For large projects that existed for a long time and devs that already know cpp really well I'm not surprised they don't care as much about those things.

→ More replies (3)

26

u/tsojtsojtsoj Sep 04 '23

In the code that I wrote, I also can't remember having any instance where lifetimes were an issue. However, sometimes you'll work with people who aren't yet experienced in C++ and the responsibilities that come with using it. In that case, it is very helpful to have the compiler stop a big category of issues that C++ beginners might run into.

23

u/[deleted] Sep 04 '23

Exactly the main issue with C++ is that in my experience most people who "know" cpp learn it in college is an opinionated C++03 version in which smart pointers and move semantics aren't a thing, is more C with classes than Cpp.

If I start a new project with a team I will 99% sure to choose Rust over Cpp if only because the compiler will force the team members to be careful instead of me going crazy in code reviews.

11

u/isht_0x37 Sep 04 '23

Yeah that is the point. To make sure other's are not writing stupid code. I have fell into race conditions many times in Rust using RwLock and the Dashmap crate, which is a fast and concurrent (read heavy) implementation of RwLock.

If you're not careful, the compilers cannot save you from semantic issues, that's no better than C++ imo.

→ More replies (1)
→ More replies (5)

5

u/GregTheMadMonk Sep 04 '23 edited Sep 04 '23

I've actually had a lifetime-related bug today for the first time in a long time. Returned an object constructed with a reference to a pass-by-value function argument. It's been a long time since I've made this mistake and hopefully a long time before I make it again. It's not _that_ big of a deal, really

→ More replies (12)

2

u/[deleted] Sep 10 '23

How is security an issue when 99% of datacenter machines boot with mitigations turned off?

1

u/isht_0x37 Sep 18 '23

Not all code runs in data centers. Most of it runs on user devices. What do you mean?

→ More replies (1)

203

u/msqrt Sep 04 '23

I've tried Rust briefly. There is definitely a peace of mind you get from knowing that the compiler can catch many more errors before of time. But personally it wasn't enough to switch ecosystems and ditch a language I know fairly well for one that would require a somewhat serious effort to learn.

I feel that C++ might be losing a lot of ground to new languages in the near-ish future, but I'm not eager to be an early adopter in this process. I'll see how the landscape turns out first.

93

u/heavymetalmixer Sep 04 '23

There's also the fact that C++ is constantly improving, not as fast as it should but still.

27

u/Sudden_Job7673 Sep 05 '23

A big challenge C++ has, is that post-internet the mechanisms aren't there to improve as fast as other ecosystems.

Lack of a mechanism to do changes that would otherwise break at compile time, lack of consensus on what idiomatic C++ is (does it have exceptions?), lack of an unstable C++ with enough adoption to try out new ideas and binary stability making it very difficulty to course correct after something enters the standard.

16

u/jgaa_from_north Sep 06 '23

The rate and scope of the changes are one of the reasons I'm looking closer at Rust right now. It's my Summer Vacation "project".

When C++ changes you are assumed to understand the new way and the old way. The total of what you need to know increases at a high rate in a language that already is pretty damn complex. I don't envy those who learn C++ today.

Also, the changes does not handle some of the most pressing issues one faces with C++, like the lack of a standard build system, a standard package manager or repository infrastructure. When a project grows, managing the - often conflicting - recursive dependencies is a pain.

I have used C++ as my primary programming language since 1996. I have probably written more than a million lines of C++ code. I still like C++ more than any other programming language I have used. My point is that the changes/innovation in the standard is a two edged sword.

→ More replies (27)

36

u/dzordan33 Sep 04 '23

Low entry in rust ecosystem is big plus. In my opinion it's easier to hire smart programmers that can and want to learn rust than experienced c++ developers.

11

u/DeGuerre Sep 06 '23

I find it hard not to interpret this as "it's easier to hire inexperienced programmers than experienced programmers", which seems vacuously true.

→ More replies (5)

19

u/Thormidable Sep 05 '23

Most c++ "problems" rust aficionados claim to solve are already solved. (Memory leaks and buffer overruns).

I appreciate rust might have a place, but to me, it feels like it is too constraining.

29

u/matthieum Sep 05 '23

Uh... You must have spent time with the wrong aficionados, because that's entirely bogus.

Rust doesn't claim to solve memory leaks. Like, at all. In fact, you can use std::mem::forget(your_value) and it'll forget it -- ie, it won't run the destructor -- or the more explicit Box::leak which converts the Box (the equivalent of std::unique_ptr) to a mutable reference which will leave forever (since it's leaked).

Similarly, Rust doesn't claim to solve buffer overruns, though its standard library does make bounds-checking the default, and requires unsafe blocks to perform unchecked accesses.

What Rust solves is temporal memory safety issues -- ie, use-after-free and double-free.

→ More replies (13)
→ More replies (2)
→ More replies (2)

34

u/eyes-are-fading-blue Sep 05 '23

Rust is a good language with a modern ecosystem. Their community is probability the worst, though.

I personally like the freedom in C++. I do not see myself switching.

8

u/peripateticman2023 Sep 05 '23

Rust is a good language with a modern ecosystem. Their community is probability the worst, though.

Pretty much this.

→ More replies (1)

24

u/lightmatter501 Sep 05 '23

Anyone who says Rust fixes all C++ issues hasn’t used them both for long enough. There are still things that C++ can do that Rust has no way to express cleanly (ex: bitfields), and things that are much nicer in C++ (some types of metaprogramming).

What I’ve found is that Rust is much better than C++ at creating well-defined interfaces, mostly due to the borrow checker. This makes using libraries much easier because their interface contract is very explicit and mostly enforced by the compiler. Rust also has more powerful metaprogramming than C++ (ex: sqlx and type-checked sql against a db at compile time). Derive macros (C++ needs static reflection for them) are very good at reducing boilerplate.

C++ is also better at getting the last 1% performance out. Rust doesn’t have stable simd and llvm misses some copy elision opportunities.

I would say that if you and everyone you work with already know C++ and can enforce memory safety, Rust is mostly a question of whether the potentially reduced ecosystem is worth the better tooling and developer experience. If you have a bunch of people who are new to systems programming, Rust is MUCH better because it beats good habits into you.

From Rust, I think that C++ should take editions as a way to add new keywords and make syntax changes. Ideally the first one should ban the C preprocessor and enforce modules.

9

u/Sudden_Job7673 Sep 05 '23 edited Sep 05 '23

Ideally the first one should ban the C preprocessor and enforce modules.

Oh, what a dream!

At that point haven't you basically bailed on inter-op between cpp-old and cpp-new though? It feels like a handful of solid "painted ourselves into a corner" features like #include, non-destructive move, etc. have been a big part of why we're talking about Rust and other potential successor languages.

→ More replies (20)

3

u/matthieum Sep 05 '23

There are still things that C++ can do that Rust has no way to express cleanly (ex: bitfields),

Are bitfields finally properly specified?

I really wish they were usable to read/write specific formats, but in the absence of a guarantee of where the bits end up, you still need to write an abstraction layer for it yourself anyway :(

→ More replies (8)

108

u/Orthosz Sep 04 '23

I'm language agnostic. They really are tools, and some tools better express problems than others.

I've done a fair bit of Rust in my private programming (work is C++/C#/Unreal/Python), and it's okay. I like traits a lot more than multiple inheritance. So I brought that over to C++ wholesale. Having proper sum types and matching is very nice. But I haven't had a memory leak in 10+ years.All my code is heavily multithreaded, and we occasionally have issues, but they aren't race conditions or deadlocks, it's all business logic (Order of resolution of a combat round for instance.).Rust's default const is nice?

Cargo is cool, but vcpkg does the same jazz, minus the testing built in.

Honestly, if C++ had remained stationary for a few more years (c++11 becoming, say c++15 or something) then i'd probably switch over. If it becomes the industry standard, I'll be forced to switch over. But not everything is best described in a functional programming language.

My c++ is a mix of procedural code, functional code, and OO code. We keep inheritance to a minimum, but sometimes it's nice to have a root layer for all objects so you can do nifty things to them.

Honestly, the Rust community has been very toxic in my interactions with them while learning, so I have to push through my distaste of those interactions to continue building things with it.

37

u/nihilistic_ant Sep 04 '23 edited Sep 04 '23

But I haven't had a memory leak in 10+ years. All my code is heavily multithreaded, and we occasionally have issues, but they aren't race conditions or deadlocks,

Some here are expressing skepticism about this, but this is consistent with my experience. We used to spend a ton of time on this stuff, but nowadays, it is very rare for it to ever come up. Modern coding style & smart pointers have essentially solved all this.

It would be a nice to go from "very rare" to "literally never" (like Rust guarantees), but really, it wouldn't change much for us. It sounds odd, but things like Victor Zverovich's fmt library coming out was a much bigger deal for us than getting good compiler enforced memory/thread safety would be.

22

u/Orthosz Sep 04 '23

The fmt library is...I can't even put to words how beautiful, simple, and elegant. It just works, and is fast..I could continue, but it's an amazing achievement. We don't even use the STL format, just fmt so we get the updates and improvements.

14

u/DeGuerre Sep 04 '23

This is consistent with my experience, too. I can't say that I haven't had a buffer overflow in 10+ years, although I don't really write networking code in C++. But I am pretty certain that I haven't had a memory leak in at least that long unless I'm doing something deeply unusual (e.g. manually managing buffer cache).

9

u/Orthosz Sep 05 '23

We treat all networking packets as hostile. We lose a number of cycles verifying it six ways to Sunday, but that's a drop in the bucket compared to it going across the wire in the first place. But I'm not a network guy, I just use the systems built and sometimes peek under the hood. Protobufs and rabbit with some validation layers seems to be what the network folks went with.

→ More replies (1)

33

u/LeberechtReinhold Sep 04 '23

Cargo is cool, but vcpkg does the same jazz, minus the testing built in.

You can't be honest saying this. vcpkg is nowhere near as good to use as Cargo. That's not a dig into vcpkg, building C++ is notoriously complicated especially because of legacy reasons, but still, the experience of bringing a lib is very different from cargo to vcpkg.

Also not a single memory leak, race condition or deadlock in heavily multithreaded code, in 10 years? That's certainly the first time I have seen or heard of such codebase. If its true, my most sincere congratulations.

I agree that C++ flexibility is nice however, while Rust really forces more into one style.

22

u/Orthosz Sep 04 '23

Please don't read into what I wrote more than I wrote. vcpkg does the base job of fetching and configuring packages, libraries, etc for inclusion. No fetching off random sourceforge or github or random websites, then figuring out how to build it, blah blah blah.

Is it as nice as cargo? No. But does it get the job done on Mac, Windows, and Linux? Sure.

And the 10 year claim was on memory leaks. Across 4 companies actually. We check before we ship our software that memory isn't leaking, it's not hard. I personally check as I'm developing, and there's tools to detect unreachable memory at program exit.

And no, generally we haven't had any issue with multithreading. Everything becomes a job on the job system. This pattern doesn't fit every problem, but it fits a lot of them. It's a pattern i've encountered time and time again, threadpool+job system. Submit jobs that do work, don't have two jobs working on the same slice of data. If you have to have them working on the same slice of data for some reason, scope lock with a mutex. But generally just give different jobs different parts of the array to work on in parallel.

Where we hit issues is with business logic tangling the order of operations, not the underlying c++ deadlocking.

27

u/plastic_eagle Sep 04 '23

Also not a single memory leak, race condition or deadlock in heavily multithreaded code, in 10 years?

That's probably a slight exaggeration, but I'm going to make a similar claim.

I've been working on a heavily multithreaded C++ application, and we haven't had a memory leak, deadlock or race condition in a similar time period. This is because

  1. We never use new or delete anywhere. The static analysis step will break if we do, and we go and fix it.

  2. We never share state between threads, except via single heavily-tested library. All other thread interaction is via message-passing, which is also heavily-tested.

Now, naturally, there have been a small set of instances in which we did leak and/or deadlock/crash. However, finding these problems has always been relatively easy.

I find it highly unlikely that Rust prevents deadlocks in any case.

We didn't need another language for everyone to learn, and certainly not one with the strange politics of Rust. What we needed, and still need, is a sane build system for C++. But that's not a very sexy problem to work on, so people keep making new languages instead.

9

u/kneel_yung Sep 05 '23

Also not a single memory leak, race condition or deadlock in heavily multithreaded code, in 10 years?

Maybe not none whatsoever, but I believe the gist of it, they're really not that hard to avoid if you use best practices, think about your design, and have even very basic code reviews.

Deadlocks/races/use-after-free are very rare in the codebase I work on with 4 or 5 other people. The vast, vast majority of our bugs are logic-related, from not fully understanding how our own system works (its' a very large codebase).

The scope of locks and race conditions and stuff like that tends to be limited compared to the sheer size of a distributed system. If you keep your modules/systems compact, it's really pretty easy to keep them deadlock/segfault-free.

4

u/caroIine Sep 05 '23

I'll also repeat what others have said I work in solution with 250 projects. Enormous codebase written in c++11 from scratch (now we allow c++17). Compiled on all platforms using (gcc,clang,msvc). And we only get logic errors where something is not presented correctly to the user.

4

u/ArkyBeagle Sep 06 '23

Also not a single memory leak, race condition or deadlock in heavily multithreaded code, in 10 years?

It's more common than you'd think. Think observer bias. Remember, something that doesn't crash doesn't make headlines.

After a few years of practice, my experience is that most teams reach this sort of state if they last long enough.

→ More replies (22)

28

u/epyoncf Sep 04 '23

"Rust fixes all the issues C++ has"

I have two issues with C++. One is that its hard to find people locally to work with on my C++ engine without breaking the bank. I guess Rust solves it - there's no one locally that knows the language in the game development space at all, so solved?

The other is long compilation times.

Well....

→ More replies (7)

9

u/chakani Sep 05 '23

Qt is a good reason to use C++. Qt is amazingly productive.

8

u/JumpyJustice Sep 04 '23

I have read rust book which poped out first in google. I liked cargo, liked syntatic sugar there. Even written a simple chat app with gui and server for it.

But it was really painful sometimes. So what I would prefer ? Well, the only place where I can select which language to use is pet project. And rust is really bad choice for it. It forces me to write sode which handles all errors and all lifetimes. But I am not launching a rocket to the moon, I just want to quickly write some prototype which runs on a pile of implicit promises (that will be satisfied in 99% of cases, though), not spending hours wrapping everything into right combination of wrappers (rc, box, ref cell, etc) to shut up the borrow checker. So it simply does not solve any problem for me (except maybe package mangement) but adds some headache for no reason.

6

u/ttesla Sep 05 '23

As someone working in game industry, in order to switch to Rust. All in house and commercial C++ game engines needs to be re-written in rust. Or else what I'm going to do with Rust?

I've never came across to a job openings which requires Rust. Even more, I have never seen it as a plus requirement. (I've seen python, JavaScript as a plus btw). I wonder if Rust is that superior, why nobody requires it?

C++ made possible almost all the AAA games. And yes with raw pointers, pitfalls and all the curse it carries. What has Rust achieved so far? Other than being cool and advertising itself as a better C++. Free market doesn't work like that. Make game engines, working examples then the industry will follow.

6

u/SweetBeanBread Sep 05 '23

your friend doesn’t represent the whole rust community. please don’t take it like an official statement by the project.

Rust does prevent many errors C++ is prone too, but by far not all. it also doesn’t suit all C++ use cases. one such case is when you are working with a C++ library

6

u/subrfate Sep 06 '23

"Fixes all the issues C++ has"? Yeah, ignorance. One of the largest gaping vulnerabilities in the past couple years was inside a Java library where said vulnerability wouldn't be detected by any of Rust's magic fairy dust.

As rust applications increase in number, there's also numerous new CVEs being entered. You don't get security by language choice.

I'm still using C/C++ for a handful of reasons:

  • team is knowledgeable in C/C++ and we have 'real work' to do

  • API delivered by vendors are written in C/C++ and can be used as-is without any additional work with ready implemented samples

  • one set of applications are simple (sub 1k) programs that read/write hardware registers and are written to coding standards restricting C/C++ features already in situations where toolchain validation is required.

  • toolchain validation is possible against a standard with multiple vendors.

  • modern C++ provides primitives and patterns for memory safety

  • sometimes an OOP solution is a good choice and Rust just isn't

  • ABI stability allows shared libraries and easier artifact management of binaries.

  • Rust's cargo introduces huge liabilities as it is sprawling in ways very similar NPM / Pypi making library updates and code auditing painful; build-time crates can hit databases or web endpoints

  • C++ IDE tooling is far more established with multiple supported options

  • my personal interactions with the Rust community and watching the Rust community interact with themselves have left an exceedingly bad taste in my mouth.

Last point is kinda the biggest TBH. After advocating for rust adoption, I'm just burned out. Rust community generally responds to needs contrary to rust by "you're not doing it right" sort of rhetoric. And sadly, the vast majority of people voicing such concerns don't have the weight of Linus threatening to axe Linux's rust integration when advocates duck hard business requirements unkind to Rust's methods.

I still got a couple toy projects at home in Rust, but selling a migration at the office is on ice for me for at least a few years.

6

u/soontorap Sep 06 '23

I tried Rust for a few years and _moved away_ from it.

The reason was not even the language, which I tend to like, though to be fair, a large part of the benefits can be transported into other environment by sticking to well-inspired and rigorous coding practices.

No, the main reason was the community. I found the Rust one to be downright toxic. Always piling onto others languages. It's not enough that their language is "the best", other ones must be bad too. And now there is a cesspool of bad faith complaints that they constantly nurture, anyone who doesn't immediately agree with them is at best a poor moron, at worst a foe to take down.

But even within the Rust ecosystem, sticking to topics that touch Rust only, there is this pervasive culture of "I know better", "this is the way it must be done" "you can't understand you moron", etc. Many times I've received "advises" about the "proper way it should be done", which were completely out of line of Rust idiom, but tend to fit a particular narrative (use my cargo library) (I used to do that in JAvascript / Python, so that's the right way), etc. No step back, no capability to ponder, adjust, learn, doubt, etc.

And this is no surprise when I look at the leaders of the movement. That's the way they behave too. Damn, they can't even bear with each other, their subcommittees have internal fights ! So unsurprisingly the rest of the minions just follow with the same attitude.

It's a shame really. Maybe Rust had a chance to be the language of the decade, but the community sure has blown this chance. I'm not touching Rust again. Culture is the most difficult part to change in any organization. It will be faster to wait for the good parts to trickle down into other more established languages.

16

u/nomad42184 Sep 05 '23

I have been programming C++ for ~20 years. I still use it regularly for projects (scientific software) developed in my lab that we originally built in C++. That said, I have moved to Rust as the default for all current and future projects.

I don't from where in the Rust community you heard "Rust fixes all the issues C++ has"; I personally never heard this, and it wasn't my reason for choosing to move to Rust. Rather, those reasons are that C++ has become monstrously complex, and while there may be a smaller, cleaner, safer language hiding within the latest standard — it often seems to be covered in a tremendous amount of complexity, and you can't easily control the features used by the 3rd party dependencies you use. For me, Rust brings a lot of modern features and idioms to the software we develop, while dropping a lot of the esoteric footguns of C++. Further, as much as I've learned to work within the C++ memory model, use modern smart pointers where feasible, and rely on RAII as much as possible, there are still plenty of opportunities for segfaults that Rust just eliminates. The sheer number of places where UB can creep into even well-designed C++ code should, I think, be terrifying.

Moreover, another major reason we've moved to Rust is, as you suggest, the developer tools and ecosystem. Since I run an academic lab, software maintenance is a funding challenge (i.e. most funding agencies don't want to pay to maintain academic software, but I don't want to let software that people actively use die). The Rust ecosystem makes getting a project up and running, controlling build dependencies, and producing a mostly static and widely-usable executable a rather trivial exercise. CMake, on the other hand, is somewhat what I imagine my personal hell would be like. Cargo, clippy, built in testing, etc. — having these things as first-class members of the ecosystem make maintaining software (at least for a small team like an academic lab) sooo much easier than it is in C++.

So to answer your question: I grew up on C++, I follow the latest standard and adopt the latest features and best practices when I program C++, I'm not religious about it and use it when I have to for legacy projects. However, I absolutely prefer Rust for new and ongoing projects, and I only imagine that sentiment growing stronger into the future.

17

u/YARandomGuy777 Sep 04 '23

I used Rust to some extent and to be honest, besides pattern matching, very convenient destructive move, excessive use of restrict in compiled code, pd_sort as default qsort algorithm and channels in std, there's no other advantages for me. Whole borrow checker thing is just looking for troubles and unreasonable restricting yourself in the ways you can write the code. And even with this strict borrow checking, Rust still have duck tape to work around it like RefCell which performs borrow checking in runtime and may crush perfectly reasonable and valid application due to borrow checking rules violation. Rust is too rigid in its ways of writing code. It is very uncomfortable for me as developer to work in one paradigm. It is fine and even enjoyable for relatively small applications with predefined and simple design with no ambitions to grow. It is like having one fancy hatchet for all carpentry work. Fine for making simple tables and chairs. But I would prefer to have a fool tool belt to build a ship or house. Macroses another questionable decision in language design. And people unfortunately use them a lot. It is quite irritating to have some silently defined objects and altered syntax. Look at Tokyo lib for example. Another issue of Rust is necessity to have wraps over libs made on other languages. It is quite annoying that you have to use other guy wrap or wrap it yourself. Additional code always means additional pain and additional point of failure. If you writing something that uses third party libs or OS API a lot, I wouldn't even consider using Rust tbh.

→ More replies (8)

17

u/germandiago Sep 04 '23

I think in theory C++ is not as safe as Rust. But in practice and with good warnings setup and smart pointers it is very safe.

On the other hand, not all are advantages in Rust: there are valid code patterns not allowed that add ceremony, it is more difficult to ise FFIs for C and C++ and with real-life projects you will always have "unsafe" code somewhere.

Also, C++ ecosystem has a ton of IDEs and libraries.

All in all, I would choose C++ just for the ecosystem alone.

9

u/Orthosz Sep 04 '23

Rust also doesn't ship on all the platforms I need it to professionally yet. They'll get there.

The other thing i've noticed with every shiny new language is that while it's new, there's no cruft built up. Everything's pretty. After 15 years, every language has weird sharp edges and grungy corners that people don't want to look at. (See Ruby, Python 2, Java, C++, D, Go)

3

u/tialaramex Sep 06 '23 edited Sep 06 '23

There are things in Rust's standard library that are regrettable already after 8 years, inevitably. Rust has a stronger compatibility promise than C++ so it won't ever fix most of these.

Ex 1: Unlike Unicode predicates like char::is_whitespace the ASCII predicates char::is_ascii_whitespace and kin, take &self, a reference rather than just self. This is a legacy of an earlier design in which such functions might belong to a Trait instead, and so it's conceivable you are asking whether some complex type (to which a reference may be cheap) is ASCII whitespace, not char, a trivial Copy type that fits in a register. As a result you can write "Some words".contains(char::is_whitespace) and that works, but you can't write "Some words".contains(char::is_ascii_whitespace) you need to write a trivial lambda.

Ex 2: Types having constants was at risk for Rust 1.0. It did land, just before Rust 1.0 but to de-risk this a bunch of constants also live, forever due to compatibility, in the library namespace. So core::u8::MAX exists, it's a u8 with value 255, but since types have constants, so does u8::MAX the exact same value. The one in core is deprecated but will by policy never be removed just in case.

Ex 3: std::mem::uninitialized<T>. For such a bare metal language like Rust or C++ it's necessary that we can tell the compiler we want some RAM without needing to meticulously zero it or whatever. This polymorphic function was the legitimate way to describe such a case in Rust, but, it's inherently unsound for non zero-size types (ie real data, it's fine to use this function to make no bytes into say an array of zero things, but that's not very useful). Today the type MaybeUninit<T> enables Rust programs to properly describe the situation and produce correct machine code. But since it's technically possible to use the uninitialized function correctly, and it was de-fanged so it's merely very dangerous it will live in the standard library forever despite being explicitly deprecated after MaybeUninit<T> was designed.

→ More replies (2)

4

u/strager Sep 05 '23

But in practice and with good warnings setup and smart pointers it is very safe.

In practice, security vulnerabilities in C++ projects are often caused by some memory issues that safe Rust prevents.

It's okay to say that warnings and smart pointers improve C++'s safety, but they certainly don't make C++ "very safe" as you claim.

3

u/germandiago Sep 05 '23

In practice, security vulnerabilities in C++ projects are often caused by some memory issues that safe Rust prevents.

Yes, there are people juggling knives and using Win32 API coding standards almost. That does not mean you cannot do easily better.

It's okay to say that warnings and smart pointers improve C++'s safety, but they certainly don't make C++ "very safe" as you claim.

I claim it because if you do that and do not escape references you basically have very few occurrences of unsafe stuff in comparison in your codebase. Of course, the language is still unsafe and it will ever be.

Given that use-after-free is one of the worst occurences and smart pointers minus escaping .get() is basically safe.

So yes, I claim that given those practices (btw gcc includes a new warning now, it is called -Wdangling and can detect some of those occurences) you are making your codebase safer. Not safer as in "proving safety for critical systems unconditionally" but yes as in "this is not going to crash, if it ever does".

→ More replies (2)

5

u/Captain_Lesbee_Ziner Sep 04 '23

I am learning C++ right now and I thought of learning rust but decided not to after reading about it. 1, there is a bigger C++ community, especially in terms of code written. I think that Herb Sutter's cpp2 might work https://www.youtube.com/watch?v=ELeZAKCN4tY , we could have our compatability and still have safety. 2, although there are some design features of rust that provide security, alot of the security seems to come from compiler checking, static analysis... And alot of things are automatically done for you. I like to choose what I use and what I do not use. I love the trust the programmer. I prefer using compiler flags. Now that is not to say that rust doesn't allow you to write unsafe code, you can, you just need to put in the keyword, but I don't like that. 3, having well trained, good programmers following strict guidelines would help. Use the core guidelines with your compiler. Microsoft and clang have their adaptations of this. Now rust I hear has some nice standard tools, but I think we can do that. When I get to be a more experienced programmer, that's one of the things I want to work on. Note: This is from what I have read and I am a beginner so I may be wrong, misunderstand things.... so feel free to correct me.

5

u/[deleted] Sep 05 '23 edited Sep 05 '23

For me as a long term student of C/C++ the Rust syntax is completely unreadable and unintuitive. And I just love the features and freedom of C++ so much.

I really tried switching to Rust, but having to fight with the language just to do even the simplest things is really discouraging. But I really do only small scale personal projects involving mainly math and rendering, so your experience might differ.

9

u/[deleted] Sep 05 '23 edited Sep 05 '23

I was recently very enthusiastic about C++ again, after originally dumping it in favor of Rust. The reason I was enthusiastic about C++ again was the fact that there are extensive and complete C++ libraries I would love to use that simply aren't available in Rust. Like PcapPlusPlus and Qt. The problem? Getting everything to compile on macOS, Windows and Linux, both on my local machines and on CI... This pain made me remember why I had previously turned to Rust instead of going through the pain of getting my C++ to build on multiple systems with multiple libraries. And yet again, I turn to Rust even though there are more extensive libraries for C++. I will have to write some logic manually that are already provided in C++, but that is max 1 days work due in my case. In the end I will have a greater understanding of the problem domain, and the code might even be safer than the C++ library code... because I am, at most, a casual C++ programmer, not a senior C++ dev who lives and breathes the language.

Sure C++ is a very flexible tool and lots of big software projects like UE uses it, mainly due to the performance in addition to the flexibility would be my guess. Maybe it's even the most flexible programming language available. But at the same time, for throwing out a side project where I want to write performant and productive code, the benefits of Rust are just too strong to avoid:

  • You got cargo, which solves A LOT of very painful problems around the usage of C++, especially cross platform.

  • You got opt-out safety instead of C++'s opt-in safety, which I think is a bigger productivity boost than I had originally thought

  • I find Rust code to be more descriptive due to the ML/functional inspiration, which is very nice to both understand and write. It makes things simpler than with Go, which is funny because I was previously a big Go advocate exactly because of the focus on simplicity.

  • I find the language to have thoroughly thought about and greatly improved the whole development experience, from starting to write code to the production moment where your code needs to run without random BS issues.

That being said, companies are not exactly rewriting all their C++ codebases to Rust, because the features of Rust are nice but not a must. My recommendation is naturally to do what I have done: if you have the luxury of greenfield development, I would from my limited experience with both languages highly advise you to use Rust because it really is an improvement over C++ for general purpose development.

Also here is a quote from another Redditor on the topic that I really liked:

Newer languages are generally "better" designed than older ones. "Better" here means that they are generally safer and that their features are more well suited for modern programming paradigms. This is generally expected, given that newer language designers get the opportunity to learn from a larger literature and from the mistakes done in other languages.The question that C/C++ programmers ask about Rust is whether the improvement is relevant enough to justify rewriting existing code. This is far from consensual. Rust might be safer, but it is also very opinionated on how you should write code. Rust borrow-checker gets in the way of perfectly valid C/C++ and valid design patterns (e.g. observer pattern). A rust dev might say that this is for the programmer's own good. However, for many programmers, this is the same as stating that well-established, battle-tested code and design choices need to be thrown in the bin. Definitely not an easy transition.

15

u/lordnacho666 Sep 04 '23

I feel like rust is just a very easy tool that gets you a lot of the way without much hassle. It's not just the memory safety stuff, there's all sorts of little things like checking your match conditions are exhaustive. Little decisions that are probably the right default to have, in a bag. You compile it and then if it works it's also close enough in performance to what you'd get in cpp, but in cpp you need to set a lot of knobs to beat what was the naive implementation in rust.

Cargo works well for me as well. Every package seems to work the same way, I don't run into weird problems. There's also a surprisingly large number of packages for such a young language.

But also I feel like the person who is good at one will be good at the other. They're both systems languages and so someone who understands those abstractions will be fine with either.

6

u/germandiago Sep 05 '23

-Wall, -Wextra, -Werror (if you want, -Weverything). Done.

3

u/MFHava WG21|🇦🇹 NB|P3049|P3625|P3729|P3786|P3813|P4216 Sep 05 '23

Add -Wpedantic -Wconversion and you pretty much have my default setting for GCC...

4

u/ruarq_ Sep 05 '23

First off, I completely favor C++ over Rust; as I don’t like the hype existing around the language. In my opinion, Rust does solve a few issues C++ has, maybe even systems programming languages in general, but it doesn’t solve all of them. Additionally, Rust has a few issues itself. Whenever I see complex Rust code, I have no idea what’s going on. There’s so much syntactical sugar that I can’t concentrate on reading the actual code. In my subjective opinion, the only pro Rust has over C++ is it’s toolchain. Cargo is so easy and intuitive to use, that I sometimes consider using Rust. My main problem with C++ is that it’s so complex and convoluted. And Rust definitely doesn’t solve that issue. It’s very complex and convoluted too, I see no point in using it when I already know C++ really well. I always say, if you know Rust, there’s no point in learning C++, and the other way around.

10

u/Dean_Roddey Sep 05 '23

This whole unreadable thing just wobbles my mind. You really think that someone coming from Go or Java and looking at some complex C++ template meta programming says, oh, wow, that's so obvious and easy to understand? It's just familiarity and nothing else. It's far and away the least important issue.

→ More replies (4)

4

u/Viack Sep 05 '23

I never actually developped in rust but read a lot about the borrow checker, and I have mixed feelings about it.

It sounds amazing when developping a piece of software with well defined requirements that is going to be used for a long period. In which case the borrow checker might help writing clean/safe code at the first trial, as compared to c++ (well, depending on your c++ experience)

However, at least in my daily job (small teams working on research topics), requirements are not that well defined and tend to change...not every day but quite often. The core part of the code must evolve frequently, with a half-full refactoring every now and then.

I feel like frequent changes in rust without going through a full refactoring is a real pain. Adding unforseen features without fighting the borrow checker (or using unsafe code) might require a LOT of experience.

That being said, the language seems really appealing with its standard build system and package manager.

→ More replies (3)

4

u/ManicMakerStudios Sep 05 '23

Don't be a bandwagon jumper. I think that's at the heart of it. Something new comes along and before people have even used it they're hoping that it's going to solve everything, be everything, and do everything they ever wanted.

Then they actually get to use it and it's not the messiah they promised it would be. It's just like anything people make: potentially useful but inevitably imperfect.

If not for the endless drum-beating from people who want us to believe Rust is the next big thing, what reason would you have to abandon a language like C++ in favor of it? Do you have specific reasons of your own, or do you just have the vague reasons other people gave you?

With Rust, it seems most of the hype is centered around the vague reasons people give to justify why they threw themselves at the new hotness without actually knowing whether it was worth the hype or not.

I learn a new language when I have a clear incentive to do so. Just because someone else tells me it's great isn't incentive. It's just someone's opinion. If I wanted the opinion of sheep, I'd be a shepherd.

4

u/umen Sep 06 '23

c++ need to put more effored in rest ,web servers , and microservices .

6

u/[deleted] Sep 06 '23

facebook, google, yandex, wechat still use c++ on their web servers

4

u/adam_optimizer Sep 06 '23

Right now I am working on a project focusing heavily on performance. I have created first prototype in Go: it was not fast enough. I have created a second prototype on Rust: it was faster but also not fast enough. I had to revert to C++: language I do not love but respect for what the freedom of it. It allows you making nasty things but sometimes that's what is needed.

4

u/[deleted] Sep 07 '23

Some of the pros of Rust (like cargo) are hard to pass up on, but if you're able to stick to a modern style of C++, you can get something close to the type and memory safety of Rust, without fighting a conservative borrow checker, while having the design freedom that C++ has (particularly w.r.t inter-referencing data structures and objects with dynamic lifetime). Both use RAII, so that's a win either way. But again, Rust has its conveniences though, especially for projects where when a particular milestone is hit, development ramps down, and minor maintenance happens infrequently as needed.

4

u/NoobKillerPL Sep 08 '23

I think C++ issues are a bit overblown, I can read Rust, but I'm not convinced to switch to it. Cargo is surely great thing, I absolutely hate CMake and managing dependencies in C++, but as a language to build complex stuff in it it's all right. I think the problem with C++ is that when you work on larger projects not everyone might be familiar with best practices and pitfalls of C++, so Rust maybe could be better? But also C++ has a lot to address it's issues if you use it correctly and I love the freedom it gives me to do whatever I want, even to shoot myself in the foot haha.

17

u/Dean_Roddey Sep 04 '23 edited Sep 05 '23

I've been writing C++ professionally for just about 35 years. But I've moved on to Rust, for my own work anyway. I'm still doing C++ for my job, though I will work hard to try to change that.

The thing is, there are memory related bugs out there all the time. But, in every one of these conversations, somehow no C++ developer ever has such bugs in their own code. Kind of hard to reconcile those two things.

But, leaving aside memory safety, which is an area in which Rust completely wins, it also has so many other advantages.

  • Real support for Option and Result

  • Very powerful pattern matching

  • None of the stupid duck typing of C++, which drives me crazy. I'm sick of reading a hundred lines of error msgs to find out I typed one character wrong.

  • Newbies to Rust tend to complain about lifetimes, but they really will not be used that extensively or complexly outside of fairly low level code. If they are, then probably you are writing code that's more complex than it should be. And they can make optimizations that are very unsafe in C++ quite safe, when you do need them, often with very simple lifetime usage.

  • Excellent, language level, support for slices, which is so nice.

  • Unicode strings (a blessing and a curse, but ultimately it has to be done and C++ will have to do it as well eventually.)

  • Move by default (and it's destructive.) This one thing by itself massively changes the way you work relative to C++, for the better.

  • Hardly any serious product these days is single threaded, and the thread safety in Rust is a huge benefit, because this is by far the easiest thing to go wrong in C++.

  • At first I thought doing away with constructors was dumb, but now I realize it's completely obvious and vastly better (when you have good Option and Result support.)

  • A well defined project layout scheme and inclusion system, which keeps Rust code bases from being randomly arranged based on the whims of whoever started it, and insures a new developer will immediately understand the layout.

  • A well defined style, which makes it far more likely that a new developer will know exactly how to write code that has the same style as everyone else.

  • Algebraic enums are a huge benefit. When I first started Rust I thought they were dumb, and now I hate every day at work that C++ doesn't have them. Combined with pattern matching, they are so useful.

  • Immutable by default, which is a fundamental difference for the better.

  • Consumptive parameters, which can provide a lot of the benefits of unique_ptr without it having to be a pointer. Ultimately this is just a side effect of destructive move, but it's a very specific use of it that gives an API developer a lot of control.

As to the syntax, that's just silliness. Anyone coming from another language to modern C++ would think a lot of it looks like random symbols poured out of a bowl. Once you get used to Rust it'll be just as natural as C++ is when you get used to it.

4

u/kkert Sep 05 '23

Real support for Option and Result

Especially important vs C++ codebases where exceptions are not allowed. And/Or where deterministic execution matters

I do miss C++ template power though, Rust const generics are still very basic

→ More replies (2)

7

u/Gurrer Sep 04 '23

Imo memory safety is an overused subject when it comes to modern c++.
Problems are still there, some that rust does solve, but they are not as wide spread as some people make it seem. E.g. smart pointers are available in both languages, just have to use them.
What Rust does not have is legacy baggage, and potential udef without some sort of warning -> unsafe scope ( this also means programmers can't use something like raw pointers without a clear acknowledgement that it could be unsafe. )

Rust also features some quality of life things, which tbh are the most important for me.
An official compiler, lsp, formatter, package manager etc.
All this makes things like cross platform compiling and shipping a lot easier.
I know there are package managers for c++, but they do not offer the same experience imo.

Where rust falls short is with wide library/framework etc. availability or support, this is of course the negative effect of being new, therefore not having legacy baggage.
It can also sometimes be a bit unnecessarily complex due to borrow checker etc.

In the end, modern c++ or rust are both great choices for safe but still fast code!

4

u/germandiago Sep 05 '23

It is true that package managers are not the same but go grab a project that is originally in autotools or an exotic build system that is popular enough and usable in Conan. Let us say it is a C library. Now try to use that in Rust. Good luck.

→ More replies (7)

28

u/James20k P2005R0 Sep 04 '23 edited Sep 04 '23

I've been working with C++ for years, heavily with Unreal Engine, and I have never in my life faced an issue that usually the rust community lists. There are smart pointers, and I feel like modern C++ fixes a lot of issues that are being addressed as weak points of C++

I've been using C++ for too long, and these are the things that I think rust solves

  1. The int/container.size() mismatch. Its not necessarily that bug generating, but its super annoying that containers have an unsigned size. Leads to tonnes of for(int i=0; i < (int)container.size(); i++), or using std::ssize everywhere

  2. UB on integer overflow. This doesn't crop up that often, but when it does it tends to be a big problem

  3. Actually usable sub-int sized types, aka no promotion. Implicit arithmetic promotion/conversions are an absolute disaster in C++, and trying to multiply two shorts together leads to some very bizarre behaviours. The accidental casual conversions between floats and ints in templates can lead to huge performance issues

  4. The occasional dangling reference with lambdas + threads

  5. Heap corruption. Its not common in C++, but when it happens heap corruption is one of the most insane kinds of bugs to track down. Absolute nightmare case to have some random heap corruption somewhere which was caused by a commit a year ago that only just randomly started showing up

  6. Fast + very usable + well designed standard library. Less of an issue when you live in UE land, but C++s standard library is...... bad. std::*map, *set, deque, mutex (a particularly bad offender), filesystem management, random number libraries etc are all significantly worse than they should be, and they will mostly never be fixed in C++. In Rust none of this is a problem, and it brings consistent performance across platforms and security. There's no way around it, Rusts standard library is a huge upgrade vs C++ especially in performance, and for gamedev that's a big problem

  7. The build system actually works. You can just compile stuff. It always works. You don't have to spend hours making things build

  8. Rusts aliasing model leads to better code generation. C++ is not a fast language in comparison, and the disparity is only going to get much wider

  9. Rust is evolving at a much faster pace than C++, and has a solution for both backwards compatibility and evolving the language. It doesn't accumulate defects in the same way C++ does, it can fix parts of the language. In a decade, C++ will still suffer from its warts, whereas rust is able to excise them

  10. Serialisation

  11. Lack of an ISO standardisation process, and a strong foundation with monetary sponsors. People have responsibilities within Rust and people are paid to work on Rust, the language, instead of being purely volunteers. If something breaks, its someone's job to fix it. If something needs fixing, there's a person responsible for fixing it. This isn't true for C++

  12. Rusts language development tends to be pretty open, compared to C++. This leads to a bunch of incredibly bad shit happening behind closed doors for C++, much of which has been discussed on this subreddit previously, and is why I won't touch the committee process with 100 foot pole

Downsides to Rust

  1. The compile time programming story is very weak

  2. I often feel like the sheer pervasiveness of lifetimes might be a bit overrated for non security critical code. I'd take a 95% solution which was much less invasive, but at the same time there is something to be said for how watertight it is. I'm undecided on this one

  3. You have to live in interop land for dealing with C, which is a pain, and interop for C++ is always going to be more difficult

  4. I'm not an especially huge fan of the syntax

  5. I'm especially not convinced by Rusts generics/traits. While they have some nice properties, C++s duck typed templates bring major advantages that Rust simply cannot replicate. The fact that C++ templates are syntactic means that you can build libraries that interoperate with each other, with 0 knowledge. If I have a vector type that exposes a .x(), a .y(), and a .z(), it can work with a library that has 0 concept of my vector type, and my vector type can have 0 knowledge of the library. This is a huge upside

  6. Its still in the process of sorting shit out. There's a bunch of drama that pretty regularly makes the rounds, and then they tweak stuff and fix it. It'll still keep happening for a while. Its good in the long term, but in the short term its certainly not ideal

Overall though, I think the critical issue is that C++ isn't really able to evolve correctly. If a misfeature lands in C++, and lets explicitly list the following features as being very suboptimal as context:

  1. std::set is slow, as is unordered_set

  2. std::map is unnecessarily slow, as is unordered_map

  3. <filesystem> has a problematic API, and is also full of security vulnerabilities

  4. <random> is unusable

  5. <deque> is unusably slow in a cross platform context

  6. vector<bool>, which is a favourite one to pick on, but it isn't going away

  7. Coroutines seem........... I am sceptical

  8. std::span is slow

  9. <regex>

  10. Any type which is larger than a pointer is unnecessarily slow. In a high performance language! This affects our supposedly modern replacements like std::unique_ptr, making it very much not a 0 cost abstraction. It is in fact a very expensive abstraction in some contexts

  11. <iostreams>. We're getting a wholesale replacement, but never a fix

  12. std::variant is extremely slow

  13. The layout of std::tuple isn't incredible

They'll mostly never be fixed. And that's just the ones I can think of off the top of my head. C++ has no process for fixing these issues, and many of the issues here are outside of 'C++' as a language anyway, they're wider technical issues that there simply is no solution for

Rust on the other hand is able to evolve the language, and the library, without being as aggressively hamstrung. In 10 years time, rusts map equivalent will likely still be state of the art, whereas C++s map equivalent will be extremely slow

C++ is trying to introduce a mathematical vector library, and I cannot help but think it is a bad idea. If anything goes wrong - including vendor implementation errors - it will be absolutely unfixable forever, and then its totally DoA and will never be fixed

This is the major reason I've been considering jumping ship for a while. Not because C++ is crap now, but because it clearly doesn't have the tools to become better. And Rust looks like its going to become the industry standard

17

u/johannes1971 Sep 04 '23

std::span is slow

What on earth are you talking about?

4

u/James20k P2005R0 Sep 05 '23

https://developercommunity.visualstudio.com/t/std::span-is-not-zero-cost-because-of-th/1429284

Its slower than it needs to be due to abi issues on windows. For some projects this has been a big enough issue that its motivated swapping back from std::span to raw pointer + size pairs. This is something rust doesn't suffer from due to its unstable ABI

9

u/johannes1971 Sep 05 '23

Ok, that may be an issue, but articles that make timing claims without providing measurements bother me. ABI is a lot more than just stuffing things in registers during function calls; maybe forcing more arguments to be passed in registers means more registers need to be saved around each call as well. The total effect over an entire program of such a strategy could very well be negative.

Is there any evidence that the Sys-V ABI is more efficient (in real programs, not just on carefully selected super-tiny examples) than the Itanium ABI? Or is angry handwaving around a few godbolt links the only thing we have to go on?

14

u/STL MSVC STL Dev Sep 04 '23

Leads to tonnes of for(int i=0; i < (int)container.size(); i++)

That introduces a 32-bit limit bug. Which may not be an issue for most code, but is a bug in generic code.

→ More replies (1)

7

u/SingingLemon Sep 05 '23

<random> is unusable

What's wrong with random? I thought it was one of the better parts of STL.

→ More replies (3)

6

u/lfnoise Sep 04 '23 edited Sep 05 '23

Serialization: Rust’s serde duplicates objects pointed to by Rc, making serialization of graphs problematic or unusable. The C++ cereal library serializes objects pointed to by shared_ptr only once. Point goes to C++ for this one, IMO.

6

u/ald_loop Sep 05 '23

std::variant is extremely slow

How so?

→ More replies (2)

6

u/Sillocan Sep 05 '23

Many of your last few points are very strange. "slow" in comparison to what?

8

u/James20k P2005R0 Sep 05 '23 edited Sep 05 '23

For std::span, ABI issues mean that its slower than passing two pointers, or a pointer + size. For std::variant, both the design and implementation mean that its not zero cost. For std::map, there are both implementation (abi) issues, as well as specification issues

For std::unique_ptr, its both a language and ABI issue, as the language doesn't support true destructive moves unlike rust, making it forced to be passed inefficiently

This is explicitly compared to rust, which doesn't suffer from any of these issues due to its unstable abi, and in some cases safety and better specification. The implementation of std::map can be updated in rust, while it cannot generally in C++

7

u/Sillocan Sep 05 '23

Hmm, for std::span it seems entirely compiler dependent. It should be zero overhead. But it seems like msvc has issues with it. I.e. https://godbolt.org/z/Esd1YaEjn but if you swap to gcc, they match.

→ More replies (2)

4

u/Recatek Sep 05 '23 edited Sep 05 '23

Rusts aliasing model leads to better code generation. C++ is not a fast language in comparison, and the disparity is only going to get much wider

I suspect this is counterbalanced somewhat by Rust's propensity to do unnecessary copies. See "Are we stack-efficient yet?".

Otherwise I agree with you on pretty much every point here. Some of the things that keep me (grudgingly) using Rust are:

  • the ecosystem and build system (though it isn't without its major pain points)

  • the suite of signed/unsigned/nonzero integer types and all the nice functions for wrapping/saturated arithmetic

  • discriminated unions, Option/Result, and the niche optimizations that Rust does with them

The borrow checker I can take or leave. I end up using unsafe frequently enough to improve code generation that I don't think an equivalent program I would have written in C++ would be all that different as far as safety. I can use Valgrind and sanitizers in C++ the same way I use Miri in Rust.

I desperately miss C++ templates and compile-time tools -- Rust doesn't even begin to compare in that respect. Generics and proc macros are nowhere near as powerful. Also, don't even get me started on Rust's IDE experience.

2

u/JuanAG Sep 05 '23

+1

Also i want to say thank you, i was very excited with the STL 2D library and when some years later i fount it was "dead" i felt bretayed. At least you tried to do it a reality so thanks

6

u/arabidkoala Roboticist Sep 05 '23

You don't need to announce to us, or anyone, your programming language of choice as if it's part of your identity. A programming language is a tool, and you use the right tool for the job. Only somebody who knows the problems you're working on and what research you've done can really say if you're using the right tool. Not your friend, not the creator of node, not the members of r/cpp.

I'd bet you the reason you're so on the fence about this is because part of you realizes that this doesn't really matter. If you find you made the wrong decision, you can apply your skills from you gained from your first attempt and learn the other language.

3

u/wyrmhaven Sep 05 '23

I have to say i did learn c++ back in the 90s then was pulled completely away from programming and stuff till 2018 where I started back in and the maturity of the language now was like learning c++ for the first time.

It really depends on what problem i am trying to solve but if i am needing a compact and complete solution it is c++.

3

u/[deleted] Sep 05 '23

My opinion is that even if it's true that Rust solves all the problem that C++ has that doesn't mean that Rust is overall better than C++. Some of these problems are for historical reasons, because we didn't know better back then or just because programing was different, these problems mainly are bad defaults or implicit behavior, but C++ also have some problems/pitfalls because of it complexity/power, C++ is way more powerful than Rust (that can be good or bad depending on your needs), especially in generic and compile time programing, did you ever try to use a data structure different than a primitive or a contiguous memory one (array, vector, view/slice) in Rust? It's not even funny. C++ concepts are more flexible than Rust traits and pattern matching is going to be the same (you can read the papers about it, it's in a very advanced phase) even though maybe is not as ergonomic for being an afterthought.

So if Rust have the dependencies than you need most probably Rust is the answer for you, but that doesn't mean C++ is doomed nor is a waste of time

3

u/mldqj Sep 06 '23

The problem I have with safe languages like Haskell and Rust is that once the codebase becomes large, it becomes cumbersome to change or refactor. Tiny changes will propagate through the type system, and you end up spending a lot of time just to keep the compiler happy. Everything has a trade-off. It's not always the safer the better. I feel more productive working on a C++ project with good test coverage. What C++ really lacks is a good package management system like Cargo. Before something like that is available, I'm trying to use Nix to mitigate the problem.

12

u/thisismyfavoritename Sep 04 '23

There's already been a bunch of similar threads if you take a look around. Also youre likely to find opinions that are very biased for cpp in this sub.

Personally i think cpp has too many footguns: UB, lifetime issues, data races. Well known members of the community seem to also think the same (cppfront, val, circle, carbon), yet most devs here will say the package management is the biggest issue 🤷‍♂️.

If youve been lucky to work in a codebase with experienced devs and are proficient yourself you might not have encountered those issues but know that they can be extremely common otherwise

6

u/JumpyJustice Sep 04 '23

Package manager is just an issue which we face every day. Your experience just helps you spend less time on it, but is still the biggest time consuming factor in C++. Which makes this issue the real one, imo.

4

u/Orthosz Sep 04 '23

Have you tried vcpkg or conan? With vcpkg if you're using cmake, it's pretty easy to setup a manifest file and bam, all the stuff is pulled/built/plumbed/ready to go.

→ More replies (3)
→ More replies (5)

7

u/[deleted] Sep 05 '23

I'd you've never had memory related bugs in your code while writing C++ then congrats, you've cracked the code. For the rest of us loosers, Rust provides a fast language, memory safety guarantees, probably the best package manager and many convenient features including many functional programming tools.

C++ keeps adding features to the standard library but they don't feel good to use. The OO system and the functional tools are not well implemented, so often times I find writing imperative mumbo-jumbo is the best approach, which feels really bad.

I think there are legitimate reasons to use C++, familiarity, availability of libraries are the first to come to mind but there are others. Otherwise, I don't see the point. C++ is the inferior language. Doesn't mean it's going to die, far from it, but I don't want to write personal projects in that language anymore.

4

u/germandiago Sep 06 '23 edited Sep 07 '23

Here I admit to be asking out of ignorance, but here I go:

  1. can you adjust flags in Cargo as you wish for any package individually?

  2. can you combine all your precached, debug or release or custom builds and reuse from a url including cross-compiled packages? I do this with Artifactory + Conan, and it saves me a ton of compilation time for my limited resources. Basically a machine with 32GB of RAM and a Core i5 and VMs for Windows and Linux. Mac builds are sent to my own station via buildbot.

  3. can you consume C libraries and still assume you are 100% (as the language is advertised all the time) in safe territory? or you also have to do a couple of assumptions? I assume it is the latter.

  4. Why there have been seeing some CVEs open for Rust? If it is so safe, they should not exist.

  5. how is the cross-compilation story?

2

u/InsanityBlossom Sep 06 '23

These arguments seem fabricated to me.

  1. Unlike in C++ libraries, where you often need to pass a ton of flags just to make the library compile/link in Cargo, you can pass features, i. e. conditional flags to enable/disable certain library features. The majority of the flags affect the whole compilation. Again, first we need to state the problem and then solve it using language/toolchain methods and not trying to port C++ solutions to a different language.

  2. Rust builds everything from source which means the intermediate artifacts it produces ( compiled dependencies ) are temporary and will be invalidated (recompiled) if changed. In Rust, you don't link pre-compiled binaries from one build into another - you build everything at once into a single binary. Or maybe I didn't understand your question precisely, I'm not an expert in this area.

  3. Can C++ ( or any other language do this ? ) Obviously no, not 100% safe, but in Rust it is much safer, especially if it's a well written library with a decent API. You wrap the unsafe calls into a shim layer with a strong interface requirement and forget it, the compiler won't let you misuse it.

  4. Why are there so many CVEs open for GCC, MSVC, Clang and numerous libraries? Rust doesn't live in isolation, it coexists with various platforms limitations and issues, and it's built on LLVM which has its own share of CVEs.

4

u/germandiago Sep 06 '23 edited Sep 06 '23

Unlike in C++ libraries, where you often need to pass a ton of flags just to make the library compile/link in Cargo, you can pass features, i. e. conditional flags to enable/disable certain library features. The majority of the flags affect the whole compilation.

Here you have basically a whole recompilation every time and, for what you say in the second comment, to rebuild from source every time... not very practical IMHO. It can change over time, I hope it improves, but nowadays things like Conan + Artifactory let you cache things and this is, IMHO, necessary for practical CI.

Rust builds everything from source which means the intermediate artifacts it produces ( compiled dependencies ) are temporary and will be invalidated (recompiled) if changed. In Rust, you don't link pre-compiled binaries from one build into another - you build everything at once into a single binary. Or maybe I didn't understand your question precisely, I'm not an expert in this area.

Meson build system also. And that is a problem for CI unless you can cache things. The amount of waste is enormous. Conan wins hand down here. I tell you about this because this would have been a problem to me I think. It slows down the whole pipelines (quite repetitive) by a lot.

Can C++ ( or any other language do this ? ) Obviously no, not 100% safe

What I argue here is how much safer and at which cost. If we take all C/C++ software made, then Rust will win by a long margin bc this includes Win32 APIs, COM and other things full of pointers and stuff like that. But if you pick software codebases done in the last, let us say, 8-10 years with most modern practices in (not all of them, but a representative sample), smart pointers, etc.? What would be the metric? I would say, but I do not have data, same as you, that the safety gap is not much safer and it will be probably something between a bit safer or almost same safety bc in the real world Rust is going to invoke C libraries and C++ using good practices (which is what I use, I do not measure things against what I do not do)... I never had a leak or a crash of use-after-free for a very long time. I mean years. Except, I must admit, once I made a mistake in multithreaded code that had some low-level simd intrinsics. But that could happen to you in any language, bc at the end you will have to enter unsafe land.

Why are there so many CVEs open for GCC, MSVC, Clang and numerous libraries?

I did not mean there are not. But since Rust is "the safe language", not the others, I do not see it is the safe language they advertise. It is the safe language if: you do not invoke C or C++, you stick to Rust and you do not use unsafe. So you cannot do the equivalent of a reinterpret_cast or mess with SIMD and alignment, for example.

Write all your software that way and you are supposed to be safe. You will be safe, and, as a side-effect, totally impractical as of today.

→ More replies (1)
→ More replies (1)

10

u/lieddersturme Sep 04 '23

Yes, yes, C++, Rust and programming languages are just tools, but there are some better tools than another.

Why C++:

  • Mature

  • Most of the libs, projects.

  • C++ 17 and 20 Big, Big help

Rust mmm... Has some really cool stuff, but omg: ( ....... here is a rant ........ )

14

u/100GHz Sep 04 '23 edited Sep 04 '23

Rust fixes all the issues C++ has".

https://gcc.gnu.org/bugzilla/page.cgi?id=gcc/weekly-bug-summary.html

3k bugs

https://github.com/rust-lang/rust/issues

9k bugs

Edit: for the above two data points, they are not really comparable. Explanation in the sub replies to this.

What's the reason you still prefer using C++ over rust.

"You can’t just place a LISP Rust book on top of an x86 chip and hope that the hardware learns about lambda calculus by osmosis." https://www.usenix.org/system/files/1311_05-08_mickens.pdf

7

u/Sopel97 Sep 04 '23

"You can’t just place a LISP Rust book on top of an x86 chip and hope that the hardware learns about lambda calculus by osmosis."

This is my favourite quote for functional languages now. Thanks.

→ More replies (1)

3

u/delta_p_delta_x Sep 04 '23

I love this quote.

11

u/quxfoo Sep 04 '23

3k bugs [vs] 9k bugs

That's some apples to orange comparison … how many of those 9k issues are actual bugs?

→ More replies (5)

2

u/[deleted] Sep 05 '23

Learn and use both, it’s synergetic and complimentary knowledge

2

u/Old_Lab_9628 Sep 06 '23 edited Sep 06 '23

I have done a lot of c++ professionally (but solo). I loved this language a lot because it gave me loads of confidence in how stuff works. I enjoyed multi threading while implementing low level custom tree for a crucial web service.

But i was not confident in my ability to share the project with anyone. Through the age i changed coding flavor a lot, from c with objects, to c++ std, etc.

I was fed up with dependency (non-)management, tho.

I had the opportunity to choose rust two years ago for a fresh new project. I had the time to learn, to fight the compiler against lifetimes cryptic message. And finally i understood things and became pretty efficient. I shared the project with my team, and beginners had no problem to add features to the repository.

So choosing rust will cost you time to relearn things (i enjoyed it), to express parallelism better, and to deliver bug free binaries. Beginners mistake will be corrected before commits rather than after deployment.

But, if you don't have the time, don't have the will, and work solo, why bother: c++ still is a perfect fit. And you may try rust later, because they share c ABI.

2

u/Efficient-Scheme1995 Jul 12 '24

I have worked with C/C++ for many years. I prefer to write and read C code with lightweight features of C++, e.g., class, string, vector. I'm also occasionally using Rust. I'd like to compare C/C++ and Rust in memory and ecosystem.

Memory

Memory is not easy to use, and once you gain sufficient expertise, memory is very powerful and flexible. One caveat is C++ provides smart pointers, but it's really difficult to use(at least I don't use smart pointers). Besides, there are plenty of tools to find memory bugs, e.g., Address Sanitizer and Valgrind.

For secure-critical projects, Rust is undoubtedly a better option.

Ecosystem

For serious projects, ecosystem is a big issue to consider, e.g., building toolchain and third-party libraries. For toolchain, C/C++ is very mature in all Unix-like platforms (which may also stand in Windows). Also, a large number of low-level libraries, e.g., crypto and mathematical libraries, which are written in C/C++.

Rust is cool and its ecosystem is not fully mature yet. One downside of C/C++ is lack of good package managers, and Rust has a unified package manager.

Overall, choosing C/C++ or Rust highly depends on projects and individual taste.

4

u/Skrax Sep 04 '23

Unless I get a job using Rust, I will probably not try learning it again. I went through hell and back with C++ and the one thing I realized is the following. Why would I make life unnecessarily hard by using Rust or C++, when there are a bunch of other options.

4

u/api Sep 05 '23

Depends on what you're doing, but I'm very anti-fad and not a bandwagon jumper at all and am now pretty sold on Rust. It's not a fad.

If you're doing anything even adjacent to security, my take is that within a few years anything not written in a memory-safe language will be considered dangerous or even unusable in some environments. 25+ years of history have proven that we can't sustainably and reliably produce code bases free of memory bugs in C or C++. If you look at the CVE history a huge percentage are still memory bugs (overflows, use-after-free, etc.) and it's 2023.

→ More replies (1)

4

u/_dorin_lazar Sep 05 '23

I'm sticking with C++. Rust is its own bucket of mistakes, and perhaps the most annoying is the political acumen of the community, that managed to lobby to politicians that their language is good and C/C++ bad.

That being said, Rust is absurdly difficult at times, especially with multithreading, and C++ is just... reliable. I'm fine with C++, and like you said, most of the issues Rust prides itself in fixing I rarely or never had.

→ More replies (2)

4

u/[deleted] Sep 04 '23 edited Sep 04 '23

Rust is annoying to use. Difficult to do self referential data structures. Borrow checker also gets in the way a lot even if you know for sure it's safe. Therefore it's hard to work with and iterate fast. If you know what you are doing in C++ and you work with c++ in a particular way you probably won't get on with Rust.

If you write modern c++ you'll probably like Rust alot.

All depends on your style and how you code. Obviously I'm going to argue that that iteration time and experimentation/tinkering is very important but others will disagree (they are wrong of course)

12

u/stoatmcboat Sep 04 '23

If you write modern c++ you'll probably like Rust alot.

Honestly, the more improvements I see in C++, the more I just like C++, and become less drawn to Rust. I wonder how many proponents of Rust who have it in for C++ are basing their criticism on C++98. Because that's sort of how I found Rust appealing initially - I learned C++98 when C++11 was just around the corner, and then I didn't follow the language for a long time, so Rust would've naturally looked a lot better in comparison.

→ More replies (1)

3

u/tiajuanat Sep 04 '23

Bear in mind I'm a C++ n00b with 7 years of recent active C++, but have been programming in some capacity for most of my life.

I'm somewhat torn, but got to say that Rust comes with lots of nice features out of the box, features that C++ is no where near fixing. Conan. CMake. Doxygen. Catch/Doctest/GTest. Rust has got it's own system for each of these and then some.

There are some places where it is painful though. Ownership is not always straightforward, and when partnering on Rust code with other C++ devs, it's a fight between the"right way" and the "Rust way". I was partnering up on a serial protocol last month, and figuring out which system "owns" the serial port was not trivial, and it ended up in a weird weak pointer.

Does Rust have rough edges? Absolutely. In fact, I don't think you can have an industrial system language without them, however I rarely feel that I'm fighting the language, and I've been actively using Rust for... A few months? It took me seven years to get here in C++.

3

u/idbxy Sep 04 '23 edited Sep 04 '23

I know both rust and c++.

I have worked for years in c++ in game development. Rust personal projects for a few months.

I find c++ great in pre-existing solutions like Unreal engine.

I absolutely hate c++ for personal projects and barely ever write them unless I have to.

I've written more personal projects with a few months of Rust than with C++.

Rust tooling > C++ any feature.

Edit: I feel like I'm a great cpp dev, and write good code in general, many people I know don't do that, it's a pain. Rust solves that issue too, so for team development I adore rust. Again, rust tooling.

But for things like 3D game development I would absolutely stick with cpp engines like Unreal.

Edit2: I became fluent ish in Rust after a month coming from a heavy cpp background. I say fluent ish because I ask a lot of questions still to the rust community or AI.

Edit3: I've found the rust community to be very welcoming, and I presented myself as a cpp programmer.

3

u/NullBeyondo Sep 05 '23

I've also used Rust for the cargo and the error system. And I really couldn't care less about the borrow checker. I use "unsafe" pointers in Rust everywhere; that's because my projects require performance (rendering of millions of hierarchical objects) and I won't get it with borrow_mut fucking everywhere lol. Rust's macros are also awesome. I really like Rust and I wouldn't use C++ ever again properly, but again... I'm not using Rust for "safety" or whatever the Rust community keep blabbing about.

C++ is my childhood language. I've been coding in it, molded in it; all since I was 11-12. I know the standard till C++23 and I still remember how excited I was about C++20 modules. I've coded everything in it from graphics to developing really fast radix sorting algorithms to awesome performant libraries for myself and vulkan-based simulations (even built an entire C++20 modules wrapper around Vulkan C with all the buggy intellisense).

After these many years, I only just noticed that I had always had that urge to build everything from scratch in C++; not the standard libraries, but stuff that doesn't exist in them. Just because I always hated having to install a 3rd-party library. It's not like I cannot, it's just I hate it; just f#cking hate it. Hate the random errors, hate the warnings, hate the incompatibility for whatever reasons, hated having to pull or copy the source code and have to define and build everything myself like a caveman.

But in Rust, it only takes 1 CLI command to install a library that does your thing and it compiles just fine. And this really made me feel how unproductive I was my whole life. You could just now focus on the project itself... and this was awesome for me. I was doing some research in Rust at some point and I wanted to visualize some data.. all I had to do was install plotters and plug my data and that's it.

I'm currently 21. I only switched to Rust a few months ago. Never really going back to C++ unless Rust is officially dead or smth with the all drama going on it last few months.

1

u/idbxy Sep 05 '23

Hey, I've got a similar background as yours and I completely agree with what you said. I've done more rust projects, and more complete projects in the few months I've been using rust compared to the years of C++ because I hated the lack of tools in cpp.

3

u/teerre Sep 04 '23

Unreal C++ isn't really C++. Epic has created a whole ecosystem around C++ to make your life easier. Hell, until recently you couldn't even use standard std tools in Unreal.

As for "problems Rust fixes" they are divided into two categories: categorical problems and usage problems. The former might be the case you really never cared because you don't care your game has a security flaw or a memory leak or a data race. It drastically depend on what you're doing, how many people use it, what's your budget etc. The latter I just don't see how can you say that. Do you const all your variables? Always? If not, there you go. Algebraic data types are just an enormous benefit in expressiveness. Error handling is whatever in C++ but very well defined in Rust. Have you heard of CMake? No? Lucky you. The list goes on.

I start all projects that I can in Rust. Of course, that doesn't mean much because the vast majority of my work is on projects that have existed for maybe decades.

2

u/FlyingRhenquest Sep 05 '23

I've seen a lot of promises of magic bullets over the years, and the Rust, Python and Agile fanbois all seem to be far too eager to drink whatever kool-aid is on hand. And far too dismissive of the drawbacks of their philosophy of the month. Rust is another potentially useful tool in a toolbox, but like every other tool that's ever been introduced to breathless claims that this tool will revolutionize the industry... it won't. If history is anything to go by, it will introduce whole new classes of complexity and problems, programmers will still introduce security problems in their code and the promises that it's a "safe" language will tend to lead to a very false sense of security. Just like every other language that come along that promised to solve all your problems did.

2

u/Rindixen Sep 05 '23

Rust is okay. though I've never heard of the game "C++" so I can't really give you an answer

2

u/MegaKawaii Sep 05 '23

I haven't used much Rust, but I don't really buy the idea that modern C++ is as safe as Rust or that you can write C++ just as reliably as Rust. "Just be careful" is something a C programmer might say to us about RAII, and by virtue of the borrow checker, resulting code is safer. The other side of the coin is that the borrow checker is quite cumbersome, and I find that translating some straightforward C++ to Rust complicates things. Just use the right tool for your job.

2

u/laralex Sep 06 '23

My three biggest pains of C++ are

  1. the amount of silent UBs that lurk around every corner and which are hard to keep in mind even for experienced programmers

  2. lack of library management

  3. messy standard library that wraps old mistakes in a very ugly (yet back compatible) way

Yet, I feel like it's not enough to kill C++, because it's a no brainer choice among big tech companies that hire you. And it's hard to advance in the career without getting a grasp of C++. Rust is still seen as a Unicorn that can be too costly to switch towards

2

u/solodon Former MSVC Compiler Dev Sep 04 '23

Just look at TIOBE programming languages index & see where C++ and where Rust is. Every new sexy language would appeal to have solved this and that and what not, but the ultimate test would be whether it stands the test of time …

https://www.tiobe.com/tiobe-index/

1

u/INIXIE Oct 18 '24

Interestingly, Rust vs C++ feels like Haskell vs Common Lisp: the former forces you to write solid programs under strict rules, while the latter gives you a ton of freedom, but sometimes allows you to write incredibly complex and genius code that only you can understand.

1

u/kkert Sep 05 '23

Rust is great. The only thing it really falls short at right now vs C++ is constexpr / const generics, but it has so many other benefits that for new projects it's a tough argument

1

u/qalmakka Sep 05 '23

Rust fixes a large number of gotchas that C++ has, first and foremost tooling, which IMHO in C++ is always a huge PITA. Rust works basically the same everywhere, cargo is very convenient, and cross compiling/deployment are way simpler.

The language too is IMHO nicer to use, but it's also true that an experienced C++ developer that does things the "Rust" way (use move semantics, concepts, ...) will probably committing lots of the mistakes people do when writing C++.

One thing where I think Rust really shows its superiority on C++ is multithreading IMHO, C++'s memory model is intrinsically prone to data races and it always takes a while to detect them. I have a huge UE project on my hands right now and debugging multithreading is a nightmare right now.

1

u/[deleted] Sep 05 '23

Unreal Engine has its own memory management system, which is amazing! They did that so that you wouldn't have to.

1

u/raluralu Sep 07 '23

I am biased towards Rust.

In Rust I like cargo, build system and ability to create lot of libraries and build project from own or external libraries.

I was playing around with embedded systems and was impressed by quality of embassy that is async runtime for embedded systems. Compared to C++ coroutines, async runtime seems so much better in rust. I understood how to play around that in few hours, while I still could not figure out how to write my own coroutines in c++ and what is going on. On the other hand coroutines usage in boost::asio seemed pretty simple to work with.

I also like idea of traits. I am biased towards functional programming and traits allows me to separate data and logic, while still enabling to apply OO like behaviour when needed. I don't like large classes in OO and I was never fan of design patterns.

I am currently in C and C++ but I would take some rust project if opportunity allows.

1

u/zaabson Oct 24 '23

My feeling is the opposite. I got back to write some c++ program after a while of not using it and writing a lot of rust. Only bugs I've introduced to my code were once I don't get in rust either because of the compiler or because of a higher level coding style, that makes it easier to write code without brittle parts. So alright - after a while I already remembered what are the gotchas and readjusted my coding style and expectations, but this is a constant mental effort to process all the invariants of code and make sure it's correct. Coding in rust in that sense feels more comfortable and even liberating.

1

u/mohamed_am83 Sep 05 '23

If you are in infosec, rust is a huge win. A large class of attacks becomes impossible by definition.

1

u/DeGuerre Sep 04 '23

I tried it briefly, too, and Rust doesn't fix the biggest C++ issue that I have: compilation speed.

The lack of a standard package manager is, to be honest, both a blessing and a curse in C++. Dependencies have a significant cost in the real world, especially in the spaces where C++ dominates. If it's easy to add them, it requires a lot of discipline on the part of the programmer to think hard before doing that.

1

u/progfu Sep 06 '23

One big benefit of Rust that C++ has little ways of fighting is the ease of use of ecosystem libraries without being careful. I don’t mean “easy to install”, but generally adding a library and just yoloing your way through the API will work, never crash or introduce problems.

I feel like if I ignore the counterproductive defaults in c++ I might prefer it for my own code, but as lately most of what I do uses a bunch of libraries, Rust just lets me write that code faster than anything (even python), and usually it works.

Problem is in more special code where Rust hits its limits and I start wishing I had C++. I’m just not sure if I could go back to it and work on projects of same scope/size & dev speed.

If there is one thing where people imo greatly underestimate Rust its how fast you can write it. there are definitely walls you may have to work around tho.

1

u/turingparade Sep 06 '23

I prefer Rust to C++, but because the language features of Rust are what I prefer to C++.

I love functional programming, and while Rust isn't entirely functional, it's functional enough where things just feel right. I also love being able to catch the majority of my bugs during compile time, surely as a good programmer I can do that in C++, but why even leave it up to skill in the first place?

I just love Rust because it feels like a language that programs for me, without losing the sheer power of something like C++.

0

u/Fiskepudding Sep 05 '23

3

u/DiscoVoadordeVenus Sep 06 '23

C++ is not too bad in terms of safety. The biggest problem is that people treat C++ like if it was C. C++ is much more safe than C, very much more.

There are many safety related problems with all languages. I saw some statistics in cpponsea conference lecture some days ago.

https://youtu.be/BaUv9sgLCPc?si=bwhhrReWTpWYRn4l

1

u/KingStannis2020 Sep 06 '23

Here's the thing, and I'm not calling you out specifically but rather the community in general - if you go around promoting how much better C++ is than C, you can hardly get upset when Rust users promote ways in which Rust is better than C++

And you can't laugh at the C devs saying "I don't have the issues you speak of because I write code properly" while dismissing Rust devs with the same argument.

3

u/DiscoVoadordeVenus Sep 06 '23

The bigger problem with Rust is that it doesn't have good interop with C++. There's so much things using C++ in the world, e.g:

- The game industry has no need to change.

- All scientific works using C++ have no need to change.

Only where people really need to try to reinforce their code safety for security reason may think of using Rust.

Lots of library's and API like Cuda, Directx, OpenGL, Vulkan, OpenCL, OpenCV etc etc etc.

I think Carbon language may have a high chance to be a C++ successor because its been made to have good C++ interoperability and memory safe.

-4

u/Ok-Needleworker-2390 Sep 04 '23

Package management, stacktraces, algebraic datatypes (enums with fields), clear memory semantics with borrow checking, immutable by default, no multiple inheritance, useful error messages, bettter error handling, fewer side effects, are some of the reason why I would strongly advise against starting new projects in 2023 in C++. Only reason for me to use C++ is to stick to the exsisting ecosystem.

Just even having stacktraces makes life so much easier.

12

u/Abbat0r Sep 04 '23

We have stacktraces in C++

8

u/Orthosz Sep 04 '23

Package management: have you tried vcpkg?

Stack traces: I don't think I've ever had a project that didn't generate them. Admittedly boost provided until <stacktrace> came online.

Sumtypes: yup. It's easy to port to c++, and the compiler can be set to scream if you don't handle every enum case.

Memory semantics: yes, and yet at the same time no. Doing lifetimes with c++ is pretty easy.

Error messages: I'll trade you template errors for trait errors or proc macro errors :-D. Clang’s errors are on par for the common errors with rust. Heck, even msvc has been doing much better.

Immutable by default: yup. We have a flag turned on so the compiler yells if something can be const but isn't, but its better for the default to be switched imo.

-2

u/mankinskin Sep 05 '23 edited Sep 05 '23

If you ever had a Segfault then you had the issues Rust addresses. I have been using Rust for years now and I had maybe 2 instances where I was fighting with a segfault when I was working with OS related stuff.

I also noticed that at least for me, it lifted a huge burden off my mind. I started thinking a lot more out of the box. Complicated problems suddenly seemed approachable because there was no curse of raw pointers.

Sure, C++ has smart pointers. But a lot of libraries still don't use them and you are often confronted with raw pointers anyways. Also even smart pointers can't enforce consistent lifetimes at compile time so you will get runtime exceptions anyways when you are multithreading. At least that is my guess, since I haven't been using C++ for a while, to be fair.

I loved working with C++, being completely low level, but the tooling is just outdated and the syntax is not always as concise as in Rust. Rust also isn't perfect but I think it is more minimal and even if its missing some stuff, what it does so far is solid and should be built up upon. Trait specialization is one feature I am missing but traits give way better error messages than templates. In general Rust pays a lot of attention to developer experience, which is pretty important.

3

u/DiscoVoadordeVenus Sep 06 '23

Some problems need things like pointers (e.g. double linked lists, etc). Rust offers "unsafe" code for that, but if something you'll be developing need to use unsafe Rust, what will that mean for the future? You could end up with lots of unsafe code depending on what you are doing.

1

u/mankinskin Sep 06 '23

Sure, but I have never written an unsafe code block. All of the unsafe code is in the libraries I use, and unsafe code is usually designed more carefully and tested extensively. Its much easier to worry about one or two raw pointers across maybe a few methods, than having that as the default. Even if your code has unsafe blocks, 99% of the pointers you are using are still compile time checked references.

→ More replies (2)

69

u/[deleted] Sep 04 '23 edited Sep 05 '23

[removed] — view removed comment

63

u/qalmakka Sep 05 '23

Rust make you a better C++ programmer

precisely that. 90% of the people complaining about the borrow checker IMHO do not realize that the borrow checker is rejecting their code for a sound reason, and that they would have written unsound C++ instead.

I recently started working on a C++ project with a 1M LOC, and it's the living proof that unsound C++ programs may look like they work properly, pass tests, and still have millions of data races and memory issues.

The fact code seems to work, even for years, does not imply it works properly, and that's a very scary thing with C++. C++ gives you enough power to keep a barge afloat even if it's full of holes, and it takes a lot of knowledge and analysis to avoid furthering the insanity.

Example: I just found that one of our classes had a method that inadvertently triggered a chain of events that ended up in reconstructing the current this in the middle of the function (thanks Tim Sweeney for your poorly written code), and still it worked perfectly, and had worked well for years, with only the very rare obscure bug being triggered every now and then. Such madness in Rust would have been caught instantly, because the borrow checker would have disallowed calling the method while this was held by someone else.

22

u/coderman93 Sep 05 '23

Yeah, people who complain about the borrow checker just don’t get it. They all tend to think that they are excellent programmers who know when something is safe or not and are convinced that 90% of the borrow checker errors are false positives.

And maybe for some people it’s true! But when I work on a large code base with dozens of other engineers of varying skill and experience, those added guarantees are well worth it.

7

u/[deleted] Sep 06 '23

This is especially true if the code gets refactored. Getting it right the first time is one thing, keeping it correct a whole different thing.

2

u/Ko_deZ Sep 05 '23

It is easy enough to identify most such issues by running static code analyzers as well as valgrind and other test tools. My main gripe with Rust is size and memory consumption, as most of what I do is on embedded systems that are often significantly memory limited, while still preferring to run microservices to help maintainability. Shared libraries and smaller compiled size helps a lot. While not as efficient as C, it still keeps me mostly safe from shooting my own foot through the newer features that has been added with 11, 17 and 20.

6

u/qalmakka Sep 05 '23

I worked for ~3 years on ESP32 with C++, and I must say it's better than C but it's definitely super easy to shoot yourself in the foot with memory consumption - especially if you have to turn on exceptions and/or you use STL containers. You copy a string in a loop by mistake and you risk completely fragmenting the on-board internal memory. While Rust disallows certain behaviours, there's nothing really stopping you from using unsafe in those few places where you really need it.

1

u/Ko_deZ Oct 09 '23

As I mentioned microservices, I was not entirely focusing on ESP32, but even on those devices I find that C++ tends to solve most of my worries. Unless I start using older style C++ coding, I find that fragmenting memory and those types of issues are not all that common. I have never tried Rust on the ESP though, I have more or less entirely transitioned to ESPHome on my ESP projects. It is just so darn easy.

2

u/qwertyuiop924 Sep 06 '23

I know a lot of complaints around Rust binary size is because Rust includes debug symbols by default so unstripped binaries are huge, but I imagine 20 copies of the same library would have unpleasant effects on an embedded system...

2

u/[deleted] Sep 06 '23

Huh? Why would you have 20 copies of the same library?

2

u/qwertyuiop924 Sep 06 '23

If you're working with microservices on embedded systems (I'm assuming this is an embedded linux type situation), you'd have multiple actual binaries running. Each binary would at least need to be linked to whatever library you're doing for serialization/deserialization/RPC. While 20 copies might be an exaggeration, if everything is statically linked then that code shows up once per binary.

3

u/[deleted] Sep 06 '23

You don't have to link your code statically in rust. It is just the default. While there is no stable rust ABI, as long as everything is compiled with the same version of the compiler there are no incompatibilities.

0

u/technobicheiro Sep 05 '23

Procedural macros are even more powerful than templates. Have you played with it?

It's annoying and less ergonomic but damn if it's not amazing.

5

u/matthieum Sep 05 '23

Procedural macros are even more powerful than templates.

They're quite different. Macros operate on syntax, and do not have access to type information. Procedural macros are certainly very powerful, but they're mostly orthogonal to templates.

1

u/throwaway490215 Sep 06 '23

Macros operate on syntax, and do not have access to type information.

Can you give an example with what kind of type information is not accessible?

→ More replies (3)

15

u/[deleted] Sep 05 '23

[removed] — view removed comment

-2

u/ambihelical Sep 05 '23

see u/monsoon_winds reply

0

u/[deleted] Sep 05 '23

[deleted]

1

u/Dean_Roddey Sep 05 '23

Unfortunately they probably are, for the silly reason that C++ has an ISO standard and Rust doesn't, hence the necessary regulatory check box can be checked for C++ but not for Rust, despite the fact that C++ is vastly less safe. It's pretty ridiculous but sadly true.

4

u/trevg_123 Sep 05 '23

ISO/DO certification for Rust in safety-critical is coming this year https://blog.adacore.com/adacore-and-ferrous-systems-joining-forces-to-support-rust

2

u/Dean_Roddey Sep 05 '23

That would be good.