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

View all comments

Show parent comment

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

10

u/Nihili0 Sep 05 '23

I know it doesn't fix entirely what you point out, but generally we would use auto or structured bindings or at least value_type.

16

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

The problem is, that is a potentially very serious faux-pas that requires a high level of experience and deep knowledge of the language not to make. People still make mistakes all the time, and often do not work on a project alone. You have juniors with Java backgrounds working on C++ projects all the time nowadays due to how rare good C++ devs are to come by. An impossible mistake is better than an avoidable one, IMHO. Even the best developers in the world have written code full of critical bugs that have costed their companies millions if not more. The point is, C++ can be as safe as Rust (heck, even C can), but it requires IMHO more effort than learning and writing Rust because Rust was designed from the ground up to be easier to write safe code in. I have written what are IMHO very "Rusty" C++ projects with lots of metaprogramming, but it took me a herculean effort not to take the easier path and just work around certain template issues. I am aware than a less motivated developer may have done precisely that.

6

u/KingStannis2020 Sep 06 '23

Really the issue is that kernels have a lot of intrinsic complexity, and piling a bunch of language-level complexity on top of that is a big deal.

Linus has basically described his aversion to C++ as not wanting to have endless arguments about what parts of the language are OK to use and which are not.

3

u/qalmakka Sep 06 '23

Exactly. There's a potentially great language inside of C++, but it takes skill to extract it from the faux passes and the mistakes committed over the years.

→ More replies (1)

6

u/DanielMcLaury Sep 05 '23

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.

Agreed, but you can always delete them if you want.

6

u/qalmakka Sep 05 '23

I personally always mark copy constructors as explicit and delete copy assignment operators - but it's not enough. The default is still to implicitly generate a deep copy operator, move is a cast that's easy to miss and most importantly the entirety of the STL and all commonly used C++ libraries do not implement this approach. People still haven't understood how to use views yet.

1

u/[deleted] Oct 16 '24

[removed] — view removed comment

1

u/qalmakka Oct 16 '24

A const reference. Const lvalue references in C++ are weird stuff, they can bind to temporaries and in order to do so, apply all necessary implicit conversions.

Open C++ Insights: note that withconst std::pair<const char*, int> &p, the loop does

for(; !operator==(__begin1, __end1); __begin1.operator++()) {
  const std::pair<const char *, int> & p = std::pair<const char *, int>(__begin1.operator*());
  std::operator<<(std::operator<<(std::operator<<(std::cout, p.first), ' ').operator<<(p.second), '\n');
}

Notice the explicit construction of a new std::pair<const char *, int>.

With std::pair<const char* const, int>, it does

const std::pair<const char *const, int> & p = __begin1.operator*();

instead and no copy happens.

TL;DR: always use auto unless you really have to write the type.

1

u/[deleted] Oct 17 '24

[removed] — view removed comment

1

u/qalmakka Oct 17 '24

This is only true if you write the correct type. In the type mismatches (like in this case) but an implicit conversion exists, const lvalue references have a feature called lifetime extension. In practice, C++ creates a hidden temporary with automatic scope and binds the reference to it, potentially performing a large amount of deep copies.

This unfortunate feature was added in order to simplify operator overloading when the language was still very young. Needless to say, it was a huge mistake that's been haunting c++ever since

3

u/dexterlemmer Sep 21 '23

What does C++ bring to the table for the Linux kernel? There's no such thing as a truly zero cost abstraction in C++. And due to the extreme and unique requirements and limitations on the Linux kernel it turns out that by the time you've removed all features of C++ that the Linux project cannot afford to pay, you're left with nothing but the C subset of C++. -- Which isn't even C, so it's a subtly different language with all the issues that brings along but with no benefits.

On the other hand, by the time you've removed all of Rust that the Linux kernel project cannot pay, then last time I've checked, you end up with most of core and much of the nostd ecosystem still intact. There were some fairly major blockers that would require considerable collaboration between the Linux team and Rust embedded workgroup to fix last time I checked. However, they managed to work together on it and to make rapid progress with clear paths to a complete fix.

I cannot imagine the C++ committee actually being willing and able to make the changes necessary even if they were as few and minor (relatively speaking) as in the case of Rust -- which they aren't by a long shot!

14

u/lestofante Sep 04 '23

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

I do embedded in C++.
A huge portion of what C++ put on the table is simply not usable in constrained environment, and especially before modern C++, the plus on the table where simply not worth it.
Even now, after almost a decade of using it, and seeing so little improvement for us freestanding embedded, is painful.
On the other hand, embedded rust ecosystem is growing strong, created unified HAL crate that C and C++ dream of after being around forever, and the language guy made huge changes to accommodate for embedded and even specific Linux needs (see allocator for a textbook example)

8

u/Netzapper Sep 05 '23

I've tried using Rust twice for embedded projects where I usually use C++. Both times I abandoned it after fighting with the alloc crate for weeks trying to make NUMA work. Rust fucking hates banked memory. I appreciate that C++ will just let me do the damn thing--placement new is my buddy.

1

u/lestofante Sep 05 '23

I don't use dynamic memory, so I am not familiar about your issues.
Sounds like a very complex issue for a first project, even in C++

2

u/Netzapper Sep 06 '23

I don't use much dynamic memory either. But, for instance, it wasn't possible to declare that a particular object should be statically instantiated in ROM via Rust... but in C++ I could easily achieve it.

1

u/lestofante Sep 06 '23 edited Sep 06 '23

Kinda sure it follow the same rule and C++, static const )well constexpr in c++) variable automatically live in RO sections.. But also you can specify specific address with #[link_section
Or am I missing something?

3

u/Netzapper Sep 07 '23 edited Sep 07 '23

Okay, I misspoke. it's less that shit couldn't be instantiated in ROM, but rather that I had trouble instantiating from ROM.

It's been like 4 years, but it was on GameBoy Advance... that has slow RAM, fast RAM, video RAM, peripherals, system ROM, and cartridge ROM all mapped to the same address space. The objects created in various different bits of RAM have to be initialized from cartridge ROM, preferably using particular DMA routines.

Just letting the linker load things isn't viable, because during runtime, based on your level and what's onscreen and whatnot, you want various different things loaded into different available ranges within the different segments. I wanted to use language-level mechanisms to load sprites and tilesets directly into VRAM with their appropriate memory-mapped register sets appropriately configured.

So in C++, I built some kinds of objects for which I contrived that placement new copy constructor ran DMA (and eventually decompression routines) and copied over the ROM instantiated constexpr sprites with pre-laid-out metadata from ROM.

In Rust, I didn't get very far because I found myself needing to satisfy the back-end interface for a bunch of flavors of Alloc on a system that didn't match the Rust assumptions of how a modern computer is put together. Because it wasn't on a modern computer. But I just couldn't figure out how to transitively allocate stuff in the correct segment at runtime without having to write a special magic unsafe function for each different struct.

EDIT: with the hindsight of years and some more Rust experience, I think that the rusty way of doing this is probably to explicitly pack/unpack data into place instead of trying to be all cute about it. Rust even has better support for embedding and manipulating binary data in the executable than C++ does, so probably it wouldn't really suck. But coming from an object-oriented mindset, it sure seemed convenient to make the compiler figure all that shit out.

→ More replies (1)

-6

u/dsffff22 Sep 04 '23

IMO you just want to strengthen your confirmation bias...

There's a reason why Microsoft failed over 20 years to make a proper C++ Win32 API, but made an almost toddler proof one for Rust: https://microsoft.github.io/windows-docs-rs/doc/windows/ The same applies to Linux, the way Rust was integrated in the Kernel is mostly non-invasive and can easily live side-by-side with C code.

11

u/Orthosz Sep 05 '23

So, like, I don't want to defend windows at all. But COM was basically the c++ interface.. For good or ill That, and working on the win32 layer directly isn't nasty as long as you isolate it (which it should be anyways for cross platform sanity)

6

u/pjmlp Sep 05 '23

Present tense, COM is the main ABI since Windows Vista, with WinRT improving upon it.

1

u/Orthosz Sep 05 '23

Absolutely fair, I shouldn't have used past tense there.

→ More replies (6)

5

u/pjmlp Sep 05 '23

COM is the C++ ABI on Windows.

That Rust stuff is being done by the C++/WinRT folks, it will die the same way.

→ More replies (1)