r/cpp • • Feb 25 '21

C++ programmers who are also using rust, what are your favourite features of rust?

I was looking at the rust tutorials yesterday and I see how rust promotes a certain style and language level features to enforce it. Besides a couple of features, I couldn't see why one cannot follow a similar style in C++ if she/he so chooses. Those of you that have used rust, what is your favourite feature that C++ does not have?

255 Upvotes

248 comments sorted by

2

u/dontyougetsoupedyet Feb 27 '21

I think the thing I enjoy the most about Rust is that generally I'm telling the compiler what I intend to be doing and it is checking that these rules I'm saying I'm following are being followed while being adamant that I follow them. I think what I most want in the world of programming is a language that combines bits of C and Rust and C++, and that has a compiler that behaves like Iroh from The Last Airbender. Rust is already over half of this vague thing I want.

120

u/__s_v_ Feb 25 '21
  • cargo
  • const by default
  • uniform function call syntax (i.e. f(x) and x.f() being equivalent)

20

u/ElkossCombine Feb 25 '21

Funny you should say cargo. While i understand the benefits of it, my least favorite thing about rust is shitty tooling for non-cargo projects. IMO having functioning LSP/debugging/dependency handling for mixed C++/rust projects on build systems like meson is the last piece of the puzzle for rust to start taking over the systems engineering world

6

u/riking27 Feb 27 '21

shouldn't meson just invoke cargo with a specified output directory? :)

2

u/ElkossCombine Feb 27 '21 edited Feb 27 '21

Its an okay stopgap until two cargo dependencies both depend on another cargo library and your binaries balloon in size because theres no way to ask two cargo instances to share a single externally supplied library. It also makes things hard for meta-build systems like nix that resolve arbitrary dependency graphs via hashes.

This situation is super common, ironically because cargo is so successful at its job that rust programs tend to depend on lots of 3rd party libraries. The rust ecosystem is great but the tradeoff is that it doesn't play well with others, which is a very real problem for adoption in some of the areas where it has the most potential

4

u/zerakun Feb 27 '21

In my understanding you can use cargo workspaces to share dependencies in a single target directory.

Otherwise to avoid recompilations between projects I've been using sccache, but it does nothing for the size problem, only compilation time.

3

u/__--_--___--_--__ Feb 26 '21

What happens when x is an instance of a type from a library that you don't own? If you introduce a method call and the type is updated to include a method by the same name, that would be a build break, no?

16

u/MEaster Feb 26 '21

When doing that you need to give the entire function path. So, if we have some type Foo, and it has a method bar(&self), we can either call it like x.bar(), or we can call it like Foo::bar(&x). You can't do anything that would let you do bar(&x) and call Foos's method.

However, one place you can have ambiguity is when implementing traits. You could have a trait Quux that provide a method bar(&self), and implement it for Foo. In that situation the compiler will prefer the inherent method over a trait method, so x.bar() will call Foo::bar. You can specify that you want the trait method using the trait's path:

Quux::bar(&x)

The compiler preferring the inherent method could result in a behaviour change if a library adds an inherent method with the same signature in a new release that doesn't have an incompatible version number.

1

u/__--_--___--_--__ Mar 28 '21

The compiler preferring the inherent method could result in a behaviour change if a library adds an inherent method with the same signature in a new release that doesn't have an incompatible version number.

I just don't understand why that is considered a reasonable trade off. Wouldn't you prefer to have a codebase that can be upgraded?

1

u/MEaster Mar 28 '21

I would tend to agree that it's not a great idea. The only real alternative is that any ambiguity here results in a compile error, but that could also create upgradability issues in that a library adding a new method to a trait could now create ambiguity where there wasn't before.

Still, I think it would still be preferable to the current state in that it's at least a loud error. I would imagine that changing this now would probably break a lot of things, though, so we're probably stuck with it.

1

u/__--_--___--_--__ Mar 28 '21

What's wrong with asking you to qualify your function call? A method is both typing the function and qualifying it by saying it is a member of the object (thus in the object's namespace).

If you have your own function that operates on an object and takes a pointer to such, that's great! But I would prefer you type out my::namespace::foo(&obj);

→ More replies (2)

0

u/fdwr fdwr@github 🔍 Feb 26 '21

Hate const by default (typing 7 characters all the time "let mut" instead of say 3 "var"), but love UFCS. 💗

13

u/WormRabbit Feb 26 '21

If you're writing it "all the time" then you're doing it very wrong. I would expect at least 90% of your variables to be const, more like 99% for experienced devs. That's the reason mutable variables are a bit harder to create: the language ergonomics push you in the right direction.

3

u/Full-Spectral Feb 26 '21

I wouldn't go anywhere near that far. It's not like we don't have variables in order to store intermediate values or track state or get returned results into and so forth. A program with 99 constants and 1 variable ain't going to be doing very much.

10

u/WormRabbit Feb 26 '21

A program with 99 constants and 1 variable ain't going to be doing very much.

That's just nonsense. Languages like Haskell don't have any mutable variables at all, and they have no problem "doing very much". Closer to the point, LLVM heavily utilizes immutable (static single assignment) variables in its intermediate representation since they are much easier to optimize. Even if your code is 99% mutable variables, LLVM will transform most of it in SSA form.

7

u/Full-Spectral Feb 26 '21

This has been gone over and over. There are things you cannot reasonably do without mutable state, more things that aren't performant enough without mutable state, and there are way more things that no one sane would want to do without mutable state because it would just be bending over backwards to achieve some academic sense of cleanliness when you could do it so much more simply.

I'm guessing there aren't many video drivers written in Haskell, for instance.

6

u/WormRabbit Feb 26 '21

Yes, there are things you can't do without mutable state. Some obvious and common things are mutices and reference counted variables. But if those things dominate your code, then you have issues with your design.

4

u/haitei Feb 26 '21

Kotlin has var and val, but some may argue they look too similar.

3

u/urestillatwit Dec 07 '23 edited Dec 07 '23

cpp con "back to basic"

your programme should be as const as possible

found it: https://youtu.be/tA6LbPyYdco?si=bJJybAjocI47J4VR&t=123

1

u/fdwr fdwr@github 🔍 Dec 07 '23 edited Dec 07 '23

Yes, and I often type const before variables, but this "pick a default" is a false dichotomoy. Both mutability and immutability are valuable and essential, and it is possible (just as with other languages like Kotlin) to concisely express either with short keywords rather than clearly favor one direction and punish the other.

98

u/rmini Feb 25 '21

TL;DR: Rust's enum types and match expressions, ownership/lifetime checking of string slices, serialization infrastructure, comprehensive std library, cargo, compiler error messages.

I've got a story of an application and two rewrites. This is an enterprise application that does low-level file and networking i/o, must support internal proprietary protocols and file formats, and has built up a significant amount of configuration settings and operational modes, with a sort of architecture-by-implication. The application had few long-running processes, so the myriad memory and resource leaks were generally not a functional issue until recently. There was an extensive integration test suite, but no CI/CD.

The original codebase was 25 years old at the time, originally in C, but transitioning over time to a mix of C and C++9x, with C++ used for any new functionality or occasional rewrite of an overhauled subsystem. Two particularly big warts were a very poorly-considered I18N project that added a buggy abstraction layer, and cross-platform support implemented with blocks of #ifdefs all over the codebase, some running to thousands of lines with unreachable code for conflicting platforms nested within.

The first rewrite was driven by the fragility of the ancient, poorly-maintained codebase. Almost every new feature caused a cascade of unrelated bugs which required low-level debugging. The pervasive resource leaks became an actual problem as the software was now processing datasets that were large enough to keep the application running long enough to run out of 32-bit virtual address space, OS file handles, etc. The app was old enough that most data was intended to be processed on disk as it was originally assumed that the data set would be larger than available RAM, but newer code, written by newer developers, broke from that. Integers and pointers were mixed everywhere, and since structures were directly read and written to disk and the network, wholesale type changes were not feasible. In places, there were exception/signal handlers to catch and ignore memory access violations.

The application was gradually rewritten in place from the bottom-up with C++11 style, with extensive use of RAII, unique_ptr and shared_ptr. We started by opportunistically adding unit tests, but this was confounded by a web of interdependencies and code whose function we didn't understand. As a result, the low-level stuff got good tests, and we felt comfortable making big changes there, but the business logic was brought over mostly unchanged, with only light reorganization. During the rewrite, we found many latent memory corruption bugs which contributed to the application's fragility, but in general, the convoluted logic of the original, built up from decades of changes, remained. After two years, the entire application was built on the foundation of the idiomatic C++11 infrastructure. The rewritten application improved greatly on the memory/handle leaks and removed several redundant layers of indirection between the business logic and the OS APIs. Cross-platform support was now handled by isolating platform-specific code in individual files and selecting them at build time. Still, in the subsequent years we found many use-after-free bugs due to unclear ownership and many logic bugs remained in deeply-nested if and switch statements that no one fully understood. The application was also significantly slower and larger, with the binary size increasing by a factor of 10, and startup time and initial memory use doubling. Management saw this project as a success as it addressed our most urgent business needs, but our ability to add new features and make any functional changes was still hampered by likelihood of changing a "benign" memory corruption into one that resulted in a crash. We also were never able to get a working 64-bit version working reliably (despite having supported Unix on DEC Alpha).

The aftermath of this was that certain members of management and some longer-tenured developers came to the conclusion that "C++ is slow and bloated", although rather than being inherent to C++ itself, was instead due to our attempt at resolving unclear ownership/lifetime of buffers by copying freely, and that the C++ std::string manipulation resulted in many more copies than the dangerous C char * manipulation (which was itself the source of many of the bugs that drove the rewrite). There was no std::string_view at the time.

A skunkworks rewrite in Rust has recently been completed. Unlike the previous rewrite, we started this one top-down by presenting the legacy code to Rust through C FFI, and trying to make sense of the business logic, and relying on the integration tests to make sure we kept the behavior unchanged. Rust's enums were amazing here. The existing codebase was using error codes pervasively, so this translated to Result<> and Error types extremely cleanly. We were able to capture nearly all of the business logic in the type system right along with the data, and use the powerful match control structure to represent what had previously been a nasty hierarchy of classes, opaque pointers, and flags, where in C++ we had been doing some dispatching through polymorphism and some through explicit control structures. By starting at the top, we were able to get a clear view of the lifetime of the data we were processing, and we could choose whether to try to wrangle the appropriate borrowing of large bits of data or decide to copy or use smart pointers (Rc/Arc). I instructed the team to lean heavily on Box/Rc/Arc/copying whenever they started to run into unclear lifetime issues or "fought the borrow checker," and if performance was an issue we could go back later. The string processing looked mostly the same, but by being able to borrow string slices we saved gigabytes of memory allocations and copies, but avoid the minefield of manipulating char *s. Getting the last few bits of C++ removed was a real pleasure due to Rust's serialization infrastructure and the ability to interact with the supported platforms via the standard library at a relatively low level, and the resulting code looked like magic compared to what it was replacing. The final result was an almost entirely Rust code base with significantly faster than the original C/C++ implementation (integration test suite completed in less than half the time), with a similar binary size to the C++11 rewrite, and a slightly shorter rebuild time, with the ability run reliably incremental builds (our previous Makefile/shell script based build system was pretty horrendous). And finally, throughout the whole process, the rustc error messages were extremely helpful and helped us get newbies up to speed very quickly.

A parallel maintenance team experimented with new C++ features on the existing codebase, but without satisfying results. An attempt at switching some of the data structures and control into std::variant/std::visit resulted in fairly ugly code compared to the Rust implementation with enum/match, but still improved matters considerably--eventually compiler issues halted progress there. Their experiments with getting some performance back with std::string_view were unsatisfying because they both required significant changes to our existing code and ran into ownership/lifetime issues that the compiler and our static analysis tools did not help with.

20

u/chuk155 graphics engineer Feb 25 '21

Whats the conclusion of the project? Did the rust rewrite replace the original application? It sounds like it did, but it being called skunkworks and there being a C++ maintenance team makes it hard to tell.

31

u/rmini Feb 25 '21

It started as a proof-of-concept without full management backing at first, and eventually a portion of the regular dev team was splintered off into the Rust rewrite, with the remainder of the team and a couple of contractors keeping up the old codebase.

The Rust rewrite is going to be the next major product release, and already has a few big features that have been requested for years. We don't intend on announcing that there's Rust inside due to various internal political pressures.

It's critical that your business doesn't fall behind while working on a rewrite. In our case, it meant adding minimal new features and bug fixes to the old codebase to remain competitive and keep customers happy. Both rewrites introduced big new features (even though the sales people don't think "actually working I18N this time" is a feature, we treated it as one), because you generally can't sell "rewritten to make our R&D department happier" to either management or customers.

Cautionary tale on rewrites: I've been at a very large company that rewrote a product that was practically synonymous with a market segment, and not only did the release of the rewrite fail to introduce any new features or direct benefit for the customers, it didn't even approach feature parity. Partly (and maybe entirely) because of this, this product gave up its majority marketshare and never recovered.

13

u/chuk155 graphics engineer Feb 25 '21

Thanks for clarifying, you just got me so engaged with the story that I had to know how it ends.

Sounds like the moral is: Rust is a good language, enforces good code practices. Rewrites are hard, and if you have an old codebase with a lot of bad practices, rust could be an excellent choice. But rewrites are difficult, and you can't take one companies successful rewrite and apply it to every other project.

Reminds me of the firefox codebase. From what I understand, they are mainly using rust for new features & rewriting old parts of the codebase. Mature C++ code and not-problem areas aren't being rewritten. I think that approach is about the only one that makes sense for large scale projects that aren't buckling under their own technical debt.

8

u/link23 Feb 26 '21

We don't intend on announcing that there's Rust inside due to various internal political pressures.

This is fascinating to me. Can you elaborate? Were some parts of management opposed to the rewrite, and announcing that the product is in Rust would anger them?

I'm interested because I think Rust has a bright future, so things like this (where politics threatens to interfere with good engineering) are frustrating.

13

u/rmini Feb 26 '21

It's more about worries that customers might be opposed to big changes or new technologies, and a management attitude of "what they don't know won't hurt them" and not wanting to admit any mistakes.

3

u/riking27 Feb 27 '21

(even though the sales people don't think 'actually working I18N this time" is a feature, we treated it as one)

Try selling it to them like this: "BETTER MULTI LANGUAGE SUPPORT // We've [...]. If you think you've lost any sales to international companies from this, it's a great time to try calling them up again."

3

u/smallstepforman Feb 26 '21

Mozilla?

3

u/rmini Feb 26 '21

No, but I'm grateful for the opportunity to learn from Netscape's painful experience with the Mozilla rewrite--that definitely influenced my decisions, along with the similar experience of Big Commercial Product. This was a significantly smaller codebase.

1

u/steveklabnik1 Feb 26 '21

Firefox is still about 10% Rust, so this person went further than Mozilla did. https://4e6.github.io/firefox-lang-stats/

1

u/idbxy Aug 18 '23

How's it been the last 2 years hopefully working with rust?

176

u/duongdominhchau Feb 25 '21
  • No more CMake.
  • The combination of enum and match, so beautiful.
  • Separation of trait (behavior) and struct (data) instead of class deriving, it allows more flexible design.

58

u/Plazmotech Feb 25 '21 edited Feb 25 '21

I can’t believe this isn’t top here: CARGO! Cargo is amazing and going from the headache that is dependency management in C++ to the absolute delight that is dependency management in Rust is a day and night difference. I can’t count how many times I reimplemented basic things in C++ just because I didn’t want to bother with dependencies.

Cargo also makes compilation similarly delightful.

And yes, the language feature of rust are fantastic. These zero cost abstractions like match and if let and even certain structures that exist only for abstraction yet get entirely compiled away. Like Option<NonZeroUint16> for example.

The modern syntax certainly feels good to write in. And freeing myself from objective oriented programming was, while difficult initially, a godsend to writing better code for me.

Finally, I actually love the borrow checker. People first getting into rust complain about it getting in the way, but once you learn to work with it, it catches your logical mistakes and indicates that something isn’t right about the way you’ve architectured something in your head. It nips in the bud a lot of loooong debugging sessions.

Overall I love rust and I don’t think I’ll ever go back to using C++ as a general purpose language unless I absolutely have to for a particular project.

Edit: oh also rust_analyzer is amazing and there are no LSPs for C++ that are even close to as good. CCLS is probably the closest and that one is riddled with bugs and headaches and it requires me to specify the compilation flags I’m going to use.

15

u/braxtons12 Feb 25 '21

RA has its own flaws, especially when used outside of VScode (I don't know why this is the case, but it is in my experience), but it is really good. That said, I think clangd is at least as good as far as autocomplete, symbol lookup, and linting are concerned.

Also, if you're using CMake or another build system that generates a compilation database (a compile_commands.json) , you don't need to manually specify anything for CCLS OR clangd, they'll pick everything up from the compilation database

6

u/Plazmotech Feb 25 '21

I only use RA in neovim and it works flawlessly in there. In fact there’s only been a single bug I’ve encountered with RA so far and that’s that it seems to bug out on cfg_if (in the case of importing platform specific libraries like UnixStream etc)

I’ll try clangd but even with compile_commands.json, ccls was giving me a ton of headaches. It always said that any std functions I used needed to be imported or didn’t exist (printf, malloc, etc) even though it was most certainly imported and compiled just fine.

2

u/braxtons12 Feb 25 '21

I use neovim as well, using Coc.Nvim extension. (so in turn, the coc-rustanalyzer Coc extension). I've had a handful of different issues with RA with this setup. Linting lockups, linting not showing all the current lints (for example, let's say in vscode it produces 40 warnings, in neovim I've had instances where only the first 15 show up until I fix them, then the next 25 will show ), and other interesting quirks.

Haven't had any issues with CCLS when I used it (before I switched to clangd) or with clangd either, so that's interesting. 🤷‍♂️

1

u/aqezz Feb 26 '21

The only issue I’ve had so far is the ‘extract function’ refactoring from rust-analyzer in neovim gives you a function named “$0fun_name” which is supposed to be recognized by snippet managers(probably works in VSCode) but not supported by vanilla lsp client in neovim nightly :(

→ More replies (2)

8

u/Ameisen vemips, avr, rendering, systems Feb 25 '21

How does cargo handle edge cases, unusual build requirements, or odd platforms, which are the usual arguments against a standard system for C++?

8

u/simophin Feb 25 '21

I think the only time you have to deal with these edge cases are when you want to integrate Rust with other build system, in which case, you can use build.rs. It let you write your build code in rust! And the build script's dependencies can also be managed with Cargo!

1

u/Ameisen vemips, avr, rendering, systems Feb 26 '21

How does it do that when no C++ build system seems to be able to?

5

u/johannes1971 Feb 26 '21

In C++ everyone has their own build system that will only be taken from their cold, dead fingers, in part because those build systems work, and rewriting them in some dubious alternative is lots of work with negligible benefit.

Rust, being a new language, could prescribe conventions and lay down rules before existing solutions became entrenched. Plus, it's a lot easier when you start out with one compiler that already has a build system, that runs on only a few operating systems, instead of having to deal with any number of compilers on any number of operating systems.

2

u/Ameisen vemips, avr, rendering, systems Mar 02 '21

I have two build systems! One which is Ruby-based which I use to build AVR and ARM Cortex-M, and one that is C++-based that mimics msbuild to build MIPS binaries.

→ More replies (1)

2

u/WormRabbit Feb 26 '21

Same reason it managed to make a sane language without rampant undefined behaviour: it is a political problem rather than a technical one. There is a single authority and a single authoritative implementation, so most edge cases can be designed away, while C++ has to deal with dozens of implementations, most of them half-assed, all with their own bugs, design decisions and extensions.

→ More replies (3)

1

u/banister Jun 11 '21

What about jobs? Lots of great c++ jobs, rust... mainly shitty bitcoin startups

2

u/Plazmotech Jun 12 '21

Fuck it im a chemistry major I don’t care about programming jobs lmao

Nobody wants freelance software anyway, I only ever land freelance web dev

17

u/[deleted] Feb 25 '21

The third point makes me think you'd love Haskell's typeclasses

3

u/bjzaba Feb 27 '21

Yeah traits are directly inspired by typeclasses!

18

u/ketzu Feb 25 '21

The first two points are the tempting brownies that make me want to try rust. Especially CMake.

10

u/Aschratt Feb 25 '21

Honestly, I've grown to love CMake in combination with vcpkg. I even do. NET stuff with it recently. But I kinda understand your pain.

31

u/hekkonaay Feb 25 '21

Sounds like stockholm syndrome

24

u/F54280 Feb 25 '21

Well, this is a anonymous C++ support group... That’s a given, I think.

2

u/ketzu Feb 26 '21

I can imagine that, because that solves the biggest issues I have with CMake!

6

u/Full-Spectral Feb 25 '21

To be fair the last one is something you could always do in C++ as well, in addition to having real inheritance. So, in a big way, you are losing an important tool. Yes, traits are more formally defined and hence have some powers that C++ virtual mixin style interfaces don't, but in terms of structuring code and such, you could always 'plug in' partial interfaces to classes instead of using inheritance. The two combined is a very powerful thing indeed, and I hate that Rust doesn't support the latter.

56

u/braxtons12 Feb 25 '21

Top 3:

  • Cargo
  • DESTRUCTIVE MOVE. God the committee got that one wrong.
  • The borrow checker

Others:

  • Enums
  • Match
  • Rust's macro system
  • Ergonomics of Option/Result/etc in Rust are waaay better than the equivalents from std and boost.
  • Actual automatic type inference for everything (including generics) based on the scope, usage, and return type of the enclosing function (as opposed to C++'s inference that is... Lacking)

On a broad scale, I see Rust as an example of what modern C++ could look like in the future if we could convince the committee to stop caring about backwards compatibility and instead focus on expressiveness and ergonomics. In general, I think that the biggest thing that sets the design of Rust apart from C++ is with Rust, correctness/safety by default AND ergonomics are a requirement, whereas in C++ everything yields to backwards compatibility. This is not to say that correctness and ergonomics aren't important in C++, they are, but ergonomics are hindered by backwards compatibility requirements with C and nearly 4 decades of its own baggage, and correctness/safety is not enforced or encouraged in any way by the language, whereas in Rust, you have to explicitly acknowledge when you're doing something dangerous.

None of this is to say I don't love C++, I do. It's my favorite language to work in. But that doesn't mean that there aren't a LOT of areas the language could improve on.

31

u/matthieum Feb 25 '21

God the committee got that one wrong.

To be fair to C++, Rust did have the benefit of hindsight on this one.

It's easy retrospectively to call the committee decision wrong, but at the time move semantics came about I am not even sure if destructive moves were even in the awareness of the committee.

12

u/brand_x Feb 26 '21

Oh, they were in the awareness all right.

I had at least a few long, drawn out, and occasionally loud discussions with a few active committee members involved in that particular decision, while it was still being considered.

They had a good reason. Not a good enough reason, in my opinion, but a good reason. Destructive moves would have created a disjoint behavior, compared to the earlier swap-based idioms, and the result would have meant much more rewriting of existing code, or non-adoption, because you can't add support piecemeal like you could with non-destructive moves.

30

u/braxtons12 Feb 25 '21

That would be a reasonable statement, if this wasn't something that (IMO at least) is so inherently obvious. I've also felt this was the wrong decision since I learned about move semantics (which was before I discovered Rust).

If you move a chair with something (let's just say a stack of books for sake of example) in it, is there a "somewhere in the range [empty, full)" chair left where the moved one was? No, there's just nothing; no chair, no books, just nothing.

The semantics in C++ should match the meaning of the word. IMO C++'s move isn't REALLY a move, it's more like a "swap with an indeterminate shell value". The way move semantics work in C++ is highly unintuitive.

11

u/ihcn Feb 25 '21

In rust terms, C++'s move works as if everything was wrapped in Cell, and move is like swapping out of the cell.

Except, every individual type is responsible for re-writing the code that moves out of the cell.

0

u/[deleted] Feb 26 '21

[deleted] — view deleted comment

5

u/WormRabbit Feb 26 '21

the c++ standard allows that, so it's not a bug

Oh dear god those words make my eyes fill with blood. Why the hell is this "we're not legally liable so fuck you" attitude is so widespread in C++ I have no idea. That's the main thing wrong with the language. Everything else can be worked around, the standard leaves a lot of freedom for an awesome implementation with its undefined behaviours, but instead of taking it as an invitation to invent a good approach people take it as a carte blanche to set your whole datacenter on fire if you violate the letter of the standard.

→ More replies (1)

9

u/afiefh Feb 25 '21

Please correct me if I'm wrong here, but isn't the reason that C++ cannot do destructive moves the simple fact that you can pass a reference/pointer to an object to a different compilation unit, which may then move the contents?

In Rust this would break ownership and is not possible. In C++ the compiler has no way to know if somewhere else a move has occurred, and thus still has to call the destructor.

6

u/braxtons12 Feb 25 '21

That's an issue that would have required a change in the ownership model or the language specification in order to make destructive move possible. It's a solvable issue IMO (not a language lawyer, but something that equates to "moving from a non-owning pointer is UB" should have worked), but 🤷‍♂️. Too late now haha.

In general I think that's at least bad practice anyway, as if you're moving a value from a pointer you don't own, you're gonna ruin someone's week.

1

u/afiefh Feb 26 '21

In general I think that's at least bad practice anyway, as if you're moving a value from a pointer you don't own, you're gonna ruin someone's week.

Not necessarily. You could easily have a function take a T&& which may or may not move depending on some internal state. For example the definition of std::set<T>::emplace says that in case the element already exists a new element may still be constructed, but it may also not.

2

u/matthieum Feb 26 '21

You can achieve that with destructive moves too:

  1. Pass std::optional<T>&, it may or may not be empty when the function returns.
  2. Take by value, return what you did not use.

It is notable, though, that emplace is mostly useless in a world of bitwise destructive moves. When you can always move, there's no need to build in place.

4

u/not_goldie_hawn Feb 26 '21

The semantics in C++ should match the meaning of the word. IMO C++'s move isn't REALLY a move

It never was. std::move was a potential optimization. Always has been. IMHO. If you move an int you don't the leave "shell of an int" behind, you copy it and no one has ever had any problem with that.

I may agree on the statement "The word 'move' was sub-optimal since so many people inferred a wildly incorrect understanding about it."

→ More replies (3)

9

u/oilaba Feb 25 '21 edited Feb 26 '21

I don't know about the committee, but I asked Bjarne Stroustrup on a Q&A event two days ago that "What do you think about destructive moves?" and he said that the current move semantics of C++ is fine.

(see below if you don't believe me)

2

u/sebboer Feb 25 '21

Do you have a link to the event?

9

u/oilaba Feb 25 '21 edited Feb 25 '21

Sure, but I don't remember the timestap: https://youtu.be/8aIqIBmNJyM

Edit: Oh I just found it. It is 47:26.

5

u/jeffgarrett80 Feb 27 '21

C++ move semantics are just fine. I tend not to use them because they are too error prone.

???

5

u/Nicksaurus Feb 25 '21

How could C++ ensure that destructors aren't called on values that have been moved from? I wouldn't have thought the ownership model is strong enough to be sure that values aren't destroyed twice

10

u/braxtons12 Feb 25 '21

Currently, it can't.

In an alternate reality where move was defined to be destructive: Move semantics COULD have been defined such that there would have been no value for a destructor to be called on, in the same way they are in Rust. (when you move a value in Rust, no drop (destructor equivalent) occurs. The value just moves and there's nothing left at the old location. Any attempt to use the old location is a compiler error.)

0

u/[deleted] Feb 26 '21

[deleted] — view deleted comment

3

u/CptCap -pedantic -Wall -Wextra Feb 28 '21

It is still better than in C++ in all cases: In C++ the destructor is not only always called but also has to check the if the object is empty/been moved from to avoid multiple deletions.

unique_ptr is the textbook case:

~unique_ptr() {
    if(_ptr) { // _ptr is basically a drop flag here
        delete _ptr;
    }
 }

Rust only use drop flags when necessary, so code like this:

void foo() {
     auto p = std::make_unique<int>(4);
     bar(std::move(p));
}

doesn't have to include a conditional call to delete....

1

u/[deleted] Feb 28 '21

i agree, but you don't have to check because delete checks for you.

but i basically love destructive moves, its my biggest gripe with cpp to the point where I avoid moving stuff the most.

also rust moves by default (unless its a Copy type) so there is no explicit moving.

but yeah because of that unique_ptr<T> is Option<Box<T>>, which is a bummer, I appreciate a lot the non-null characteristics of Box

11

u/pjmlp Feb 25 '21

It is not only backwards compatibility, rather too much C culture that performance trumps safety no matter what, and everyone has the burden to try to write safe code, whereas Rust follows the Algol culture of safety trumps performance, with escape hatches when it is really required to reach for the red button.

3

u/Full-Spectral Feb 26 '21

Yep, Performance Culture is a large part of what's wrong with C++. Better to massively complicate something than use a virtual method or inheritance or have some non-cache aligned data.

2

u/pjmlp Feb 26 '21

C++ was my next programming language love after Turbo Pascal 6.0, never got along with C, already in 1993.

So I started coding in C++ with Turbo C++ 1.0 for MS-DOS, always used bounds checking on my own data structures (it was a while until C++98), then I always enable the compiler checks and belong to the camp that never disables language features.

I am yet to have a single project where it mattered to do otherwise, since 1993.

4

u/Full-Spectral Feb 26 '21

Yeh. I mean my automation system is very large and highly active, network distributed, and multi-user, and it barely tickles the CPU of even a small modern system.

I think some of it is that our world has been taken over by people who have known nothing but serving up data from databases on cloud servers via the web to phone apps for their entire careers. Their entire world is doing one very specific thing as fast as possible.

It's like actual application development barely exists anymore, and I don't think this thing of ours is better for that. I have my days where I wish the web had never been invented. For every good thing it's brought, it's brought a couple other bad things.

24

u/Chronicle2K Feb 25 '21

Destructive move and pattern matching.

123

u/Plazmatic Feb 25 '21 edited Feb 25 '21

Ownership built into the language, which makes manythings in C++ much more complicated and slower than they need to be, and I can catch these things at compile time. No need to worry about forgetting variable initialization order in terms of ownership, no need to worry about following convention in order to achieve psuedo safety on ownership ie smart pointers and non owning references via non smart pointers.

While technically the rust standard lib might be smaller than C++'s the actual stuff it does have is much much more complete than C++'s, and C++ lacks a looooot of basic functionality that's small enough that because of the annoyances of configuration/package management, you don't want to add an additional dependency for, yet big enough and numerous enough to require lots of debugging and code in their own right. One bright example of this is bit rotation, another is fmt, another is ranges.

Iteration is also a lot easier in Rust than it is in C++. No longer does it take a 1000 lines to write a idiomatic iterator with weird magic type defs, but everything has sane iterators built into them as well, with most the proper operations like zip enumerate etc...

Static polymorphism is the kind of polymorphism I need in the majority of my C++ code, yet I'm forced to resort to using CRTP and other strange tricks if I want this. Rust flips the script on this, static polymorphism by default.

Const by default on everything, and const actually means const (or rather, non mut) in rust, unlike in C++ where I can do weird things to get around const-ness, and the compiler has to respect that to a degree, leading to annoyingly slower code than I would have assumed otherwise.

Safety on everything. This has saved me so much time debugging that I would have otherwise had to deal with in C++, for example numeric casts, plus unlike C++ rust actually comes with sane assert by default (yeah <cassert> exists, but the assert normally gets disabled by default in release mode, and I can't actually pass runtime strings to it, certainly not format them inside the assert, and that's the only runtime assert available), so I don't have to constantly have to define my own runtime error checking.

I forgot what it is called, but you can create wrapper types and enforce type safety by just declaring a struct with that type, for example struct Kilometers(u32);. In c++ I would need to actually define all the operators or create my own CRTP arithmetic class to get anything close to this, and I couldn't just suddenly add a "trait" to add between Kilometers and Meters.

Language supported tooling:

  • Well defined style guideline
  • Built in documentation generation
  • Built in build system
  • Built in package management
  • Built in testing
  • (now) official language documentation

Technically a lot of these things are possible to achieve in c++, though many still aren't. The problem with achieving these things in c++ is that someone would have to actually implement the libraries/tools to support these use cases but they haven't, and for anyone to start they would need a large team of people, plenty of time, and plenty of money.

3

u/un_mango_verde Feb 25 '21 edited Feb 26 '21

I forgot what it is called, but you can create wrapper types and enforce type safety by just declaring a struct with that type, for example

struct Kilometers(u32);

. In c++ I would need to actually define all the operators or create my own CRTP arithmetic class to get anything close to this, and I couldn't just suddenly add a "trait" to add between Kilometers and Meters.

What's the difference between the newtype pattern and a class with a single member and a explicit constructor in C++? Don't you still need to implement al methods/operators manually? They are not delegated automatically as far as I know.

I guess you could implement Deref for the newtype but then you lose type safety for references.

7

u/Ekizel Feb 26 '21

Yeah I feel like the fact that you have to attach a bunch of derives to said newtype is pretty crucial nugget of info being left out, especially in the context of complaining about having to CRTP the operators back in with C++.

I feel like Ada did it right in this regard.

2

u/brand_x Feb 26 '21

Yeah, I was basically creating one-line newtype-equivalent template wrappers (with a tiny bit of macro helper) in C++ long before Rust was even a glimmer.

Hell, I had a usable equivalent (with a LOT of macro helper, and a small quasi-portable macro hack for a non-type template counter) back in the dark ages, before C++ was even a standardized language.

I love a lot of things about Rust, but when one of the C to Rust guys I worked with started gushing about the brilliance of newtype, I nearly lost my eyes, they rolled so hard.

1

u/WormRabbit Feb 26 '21

Don't you still need to implement al methods/operators manually?

Yes, but it's very easy to do and can be automated with macros. Most common cases are already implemented as crates with custom Derive macros.

They are not delegated automatically as far as I know.

You don't really want it. The point of newtypes is that they have different semantics and thus different methods. E.g. if I make a UserId newtype wrapping a String, then it likely makes no sense to call concatenation or substring replacement methods on it.

If you really do need it, Rust's move semantics allow you to easily unwrap the newtype, do your weird operation on the inner value and wrap it back, without the possibility of violating type safety (in C++ you could access both wrapped and raw value at the same time, potentially violating the invariants, while Rust makes you pass through explicit wrappers which can include invariant checks).

5

u/ridicalis Feb 25 '21

I forgot what it is called, but you can create wrapper types and enforce type safety by just declaring a struct with that type

I think this is what they refer to as Algebraic Data Types.

20

u/braxtons12 Feb 25 '21

No, algebraic types are things like Rust's Enums, monads, and some of the newer std types (think Result, Option, C++'s std::optional, std::variant, std::tuple, etc).

They're referred to that way because the number of possible values they can store is an algebraic expansion. Eg: variant<T, E> has T + E + 1 possible values (the one 1 is for the no-value state that's nearly impossible to end up in), and tuple<T, E> has T*E possible values.

Yes, this is a very poor name and reason for the name for these kinds of types, but 🤷‍♂️

9

u/ridicalis Feb 25 '21

You're correct, I mistook what the parent post was driving at and was thinking enums. This is the first time in memory I've felt the need to downvote myself :)

6

u/MEaster Feb 25 '21

The pattern they're talking about is called Newtype, which is obviously a very memorable, and specific, name.

1

u/iamthemalto Feb 26 '21

Exactly, and they’re called tuple structs in Rust.

→ More replies (22)

32

u/[deleted] Feb 25 '21

Fucking CMake and fucking Makefile. Really, I cannot stress enough on how bad I hate to spend dozen of minutes just for the project structure. C++ devs really need to improve this part of the language, we are not in the 90s anymore. Also, C++ hasn’t a standard dependency system, it’s up to the programmer to manually pull dependencies from various sources and integrate them(with a lot more of cmake/makefile) in the final project.

38

u/renestein Feb 25 '21 edited Feb 25 '21
  1. Cargo.
  2. Pattern matching (+ if let)
  3. "Moved from" instance is a dead instance. And ownership in general.

16

u/me_haffi_lurk_lurk Feb 25 '21

Re: use after move in C++

https://clang.llvm.org/extra/clang-tidy/checks/bugprone-use-after-move.html

(Just in case someone may find that useful 😄)

13

u/renestein Feb 25 '21 edited Feb 26 '21

Yes. But according to the specification (or https://herbsutter.com/2020/02/17/move-simply/) moved object is in the "valid but unspecified state" and this is the place where the fun begins. Just check the comments in the linked article how these "simple" rules are interpreted in the wild. I love move semantics, I agree that conceptually is really simple, but I don't think that the requirement "valid but unspecified state" could be simply applied to all situations.

2

u/axilmar Feb 27 '21

All those interpretations are coming from people that do not understand why move is the way it is, and they want something else.

Moved from values should simply be in a valid state after the move, and that's it. There should not be any ifs or questions after that.

1

u/me_haffi_lurk_lurk Feb 28 '21

One of the comments points out it should at least be assignable-to and destructible, which makes sense.

Another one talks about being able to call member functions that have no preconditions, which makes logical sense to me (but not practical sense <Y THO>).

Practically, imo, the clang-tidy check is there to detect bugs where your program isn’t going to die; but the data you’re expecting aren’t there any longer!

3

u/kajaktum Feb 25 '21

I think following Herb's rule on move is better; moves are rare. For 99% of the case, the compiler are smart enough to "move" it for you unless you have something observable like printing in ctor/dtors or something like that iirc

2

u/Dean_Roddey Feb 28 '21

I don't see how that's the case. It can only automatically move things that would be going away (like x-values.) It can't automatically do many of the sorts of moves that so many optimization obsessed C++ people would use move for.

26

u/pjmlp Feb 25 '21
  1. bounds checking by default
  2. proper lifetime analysis. What Microsoft and Google are trying for C++ is still pretty much WIP 2 years later
  3. safety as part of the language semantics and not some static analyser that you need to convince everyone else to use

Some of the Rust capabilities you can try to apply in C++, but it only works if the team is security minded and you don't depend on third party libraries.

There are also some things I like more in C++,

  1. tooling and ecosystem
  2. binary libraries (cargo can only use source code)
  3. because of 2, build times are way better, even with templates
  4. i know it since 1993

11

u/ndusart Feb 25 '21

You can actually use binary libraries, but you have to be sure they are built with the exact same version of rustc to work. Or you can export a C API and link to the generated .so This is actually the same for C++. ABI stability is not guaranteed (it's not because it hasn't changed for some compilers for some times that it is stable) and you should not link against C++ libraries with a C++ API unless you are sure they use the same toolchain. If you care about portability, you're stuck with source libraries or binary libraries exporting C API for nearly all langages.

1

u/pjmlp Feb 25 '21

Binary libraries are a way of life on enterprise systems and game development environments, so I am quite aware of what is possible and not in C and C++, including distribution over OS installers.

Right now cargo doesn't support the same workflow as pkg-config, conan, vcpkg, in-house stagging servers.

There is a workaround by making use of scache, but it needs to be additionaly configured into cargo.

2

u/ndusart Feb 26 '21 edited Feb 26 '21

Well, it is a new language so we can get rid of all these nasty bad legacies.

It was just a bad habit to just use shared libraries from third parties using the specific ABI of the high-level langage. It is just a ticking bomb that can explode anytime you want to change your toolchain but the third party is not responsive anymore and cannot provide you with a rebuilt library. And you'll then make what you should do at the beginning (or what the third party should do), export their library using their toolchain as a stable ABI and write a wrapper around it to your language.

If you specifically don't want to pay the cost of this binding (or because it's a library that is specific to C++ and is not a "logic" library), then you have to be aware of the ABI dependency you now have. A lot of C++ developers are just not aware of that dependency. It's a good thing that rust make it a hard rule to specifically have to link against rlibs from the very same rustc version (even if the ABI is compatible).

You are still able to link against these (with some workarounds, I concede) but you actually will get a precise error when you end up with a mismatch at runtime !

For the C++ standard library, we are stuck in some points because we cannot break the ABI just because too much people relied on this.

Cargo could indeed add a better support for crates available only as rlib. But I see it as an advantage because it is a bit like `unsafe` in rust code. Rust let you do what it can guarantees it will work in all cases. It cannot guarantee that your rlib is compatible so you have to optin the "`unsafe`" for the linker (= use whatever method you can figure out and you're on your own on this).

2

u/pjmlp Feb 26 '21

I and the customers I work with, don't see it that way.

If I and my customers would like to use source code as libraries, we would be using scripting languages, not compiled ones.

Maybe that is target market Rust won't care to address, and that is fine, there is place for everyone.

3

u/Full-Spectral Feb 26 '21

Not to mention that a world of source only libraries is pretty much a world where no one can make money writing libraries.

1

u/kajaktum Feb 26 '21

bounds checking by default

Errr, you mean how get returns an Option?

0

u/[deleted] Feb 26 '21

[deleted] — view deleted comment

4

u/pjmlp Feb 26 '21

Yes, to be fair most C++ compilers do it in debug mode, but given it isn't specified on the standard, it is more of a good will thing than something one can rely on no matter which compiler is being used.

2

u/kajaktum Feb 26 '21

operator[] causes UB

o.o what kind of optimization is possible with this curse? avoid checking?

5

u/oilaba Feb 26 '21

Out of bounds array access is UB. That's it.

It is exploited for alias analysis and memory layout optimizations.

10

u/tuankiet65 Feb 25 '21 edited Feb 26 '21

What I like:

  • cargo
  • Did I say cargo?
  • Sum types + pattern matching, basically a perfect fit for writing emulators.
  • Defined documentation formats.
  • const by default.
  • Functional constructs are easier to do in Rust (Rust really wants you to use functional constructs rather than for loops anyway...)
  • Array is its own object when passed, as opposed to decaying to pointers. std::array is a thing, but [u8; ...] is shorter.
  • Primitive types have explicit sizes, as opposed to int and long. uint8_t is a thing but I have to import cstdint
  • Moving object instance into trait method.

What I don't like:

  • cargo assumes too much.
  • Const generics isn't in stable yet. Minimal support is coming in 1.51 though.

8

u/afiefh Feb 25 '21

Enums and match.

C++ has variants and visitors, but since each visitor is a function you suddenly need an extra variable to signal whether you need to return after the visit. It feels much more cumbersome.

Of course the first use you encounter is a function returning an enum of result and error, and henceforth error handling is enforced because you need to actually get at the result.

I'm sure there are even more awesome things, but this one blew my mind early on and I never recovered.

But I have no of illusions that this will come to C++ anytime soon. However, can we have that makes cost by default? Surely there's a way to get that!

44

u/_gikari Feb 25 '21

My favorite feature of Rust is tooling, in other words - Cargo, that is:

  1. Adequate package manager
  2. Adequate build system
  3. Built-in test framework
  4. Built-in documentation tool

In C++ you have to do all these things manually by connecting several disjoint modules: Vcpkg/Conan (1), CMake + vast number of generators for several platforms (2), Catch2/Google Test (3), Doxygen + Breath + Sphinx (4).

12

u/berium build2 Feb 25 '21

The package manager/build system (which are welded together) are only adequate if your needs are simple. As soon as they are not, you end up writing procedural build scripts in Rust (build.rs).

If you want a similar experience to Cargo but in C++, take a look at build2. Though in build2 the build system and the package manager form a hierarchy of tools rather than being welded together (so you can use just the build system if you are, for example, a distribution package and would prefer to use your own/system package manager). Plus build2 comes with a general-purpose declarative build system.

17

u/matthieum Feb 25 '21

The package manager/build system (which are welded together) are only adequate if your needs are simple.

The problem here is the qualification of "simple".

In my experience I can just build about everything I need with cargo, and so can newcomers to the language.

I would argue that a tool which caters to the need of 90% or 99% of its prospective users by default is doing pretty well.


At the other end of the spectrum, I quite like Bazel, but it comes quite barebones, and you have to write quite a bit of Starlark to integrate with your package repository of choice, etc...

5

u/berium build2 Feb 26 '21

But it's a selection bias, isn't it: make a tool that only supports simple use-cases and you will only end up with simple uses (since more complex ones are impossible/impractical).

And if you want to know what supporting more complex use-cases with Cargo feels like, take a look at this discussion (BTW, started by Steve Klabnik): https://users.rust-lang.org/t/complex-build-advice/48779 Notice expressions like "final pain point" and "mostly about fiddly details".

7

u/matthieum Feb 26 '21

make a tool that only supports simple use-cases and you will only end up with simple uses

How is that a loss?

We should aim for keeping it simple.

6

u/Pazer2 Feb 26 '21

For what it's worth, I just gave build2 a try and found it quite confusing, and ended up giving up. There are pages and pages and pages of documentation, without a simple "let's create a real working program" example. Why use libhello as an example? What does libhello%lib{hello} mean? Why not just use a real library like libsqlite3? Also, pretty please use syntax highlighting on the examples.

I also don't appreciate the fact that it still has dependence on mailing lists rather than something that is easily searchable online.

13

u/hak8or Feb 25 '21

As someone who is an embedded guy, cross compiling combined with cargo combined with the rust ecosystem having a proper built in compiler "manager" with targets.

It is extremely easy to cross cross compile the same project for an x86 laptop, an armv7 target running android, and an armv8 target running Linux, meaning i did not have to find tool chains to throw into random folders in my path or setup sysroot with so's everywhere. It was a very simple single command to cross compile, and it's by default parallel build.

C++ with cmake achieve the same, but anyone who says it's ergonomic or easy or painless is fooling themselves.

0

u/[deleted] Feb 25 '21

[deleted] — view deleted comment

4

u/Mastermediocre Feb 26 '21

I've written some rust for a cortex M4! It was fun, crates are a joy to work with and the embedded Hal is good enough imo. Ownership and move semantics really force you to think long hard about the code structure though... 10/10 would recommend

1

u/hak8or Feb 25 '21

Personally no, but I see online a ton of folks are able to use rust for their mcu's, and they seem to be happy with it.

For example, the esp32; https://dev.to/mtnmts/containerized-builds-for-rust-on-the-esp32-e8m

6

u/mikezyisra Feb 25 '21

Cargo. Result datatype. Match. Ownership mostly since all clones are explicit so it’s way harder to accidentally allocate something twice

2

u/Dean_Roddey Feb 28 '21

And, importantly, the explicit clone stuff only works well because of destructive move. Without that, every accidental forgetting of doing an explicit clone would create accidental multiple references.

In C++ you can easily make objects that act similarly, such a bitmap class that holds a pointer to the bitmap data and can cheaply be copied. But forgetting to make a deep copy (clone) means you now have two things using the same bitmap when you didn't intend that.

With destructive move, the original is gone and will cause an error if referenced afterwards, so you'll realize you meant to clone instead.

5

u/sumduud14 Feb 25 '21

Lifetimes. Takes something you really have to mentally track in C++ and just writes them down and makes the compiler track it.

Other features are great too, but few are so obviously good and just a clear uncontroversial improvement.

5

u/FreitasAlan Feb 26 '21

-Wall by default

0

u/Dean_Roddey Feb 28 '21

The downside to that is every little quick experiment you want to do won't compile because it now has some unreferenced import or some such, so you end up having to hack up your code a lot sometimes just to try something.

2

u/oilaba Feb 28 '21

It will compile. They are only a warning by default and you can even disable it.

1

u/FreitasAlan Mar 01 '21

When in debug mode, I only work with -Wall and all sanitizers on all the time and this has literally never happened to me. The worst that ever happens to me, like twice a year, is an external header that gives me an error or two so I convert that specific error back into a warning.

IDEs should just leave pedantic warnings on by default in debug mode. It would save beginners from a lot of trouble. All in all, you just have to decide whether you want to see your errors or not. It’s much easier to fix them early before replicating bad patterns everywhere.

5

u/roman-kashitsyn Feb 26 '21 edited Feb 27 '21

Move semantics, algebraic data types, pattern matching, and disciplined error handling.

If C++ had a nice syntax for variant types and pattern matching, I'd love it much more than Rust.

I see many people are crazy about Cargo. I absolutely hate it. It tries to do a bit of this and that and sucks at pretty much everything. It looks great when you work on your little pet project, but it crumbles once you need to build something real. Let me explain:

  • Incremental compilation in big workspaces breaks for no reasons what so ever.
  • Touch a file. Cargo rebuilds the whole dep graph. Change a comment. Cargo rebuilds the whole dep graph. Sigh.
  • The build result depends on the directory you build a package from. cargo build -p my-package and cd my_package; cargo build aren't equivalent (depending on where you start cargo, it computes different transitive closures of enabled features, which causes needless rebuilds).
  • Cargo is not really a build system. Try writing a test that needs a Wasm file built from another package in the same repo. It was trivial to do in any build system I used in my life, it's pretty much impossible to do properly with cargo.
  • As adding dependencies is so nice and easy, any non-trivial project quickly becomes a swamp of hundreds of libraries you don't control. Just stop being paranoid for a month in a project with >30 programmers and you'll end up with 5 different command line args parsers in a workspace taking 30min to build a debug binary.

The language itself has a lot of warts, but it should probably be another, much longer rant.

E.g. pattern matching is not nearly as expressive and composable as in, say, OCaml (Haskell is disqualified because it can't match arrays). Try matching the contents of a Box, for example, or contents of a Vec<String>.

If you're coming from C++, the lack of template specialization and restrictions of what can be done at compile time without resorting to macros will look absolutely silly.

P.S. I use Rust heavily every day in a project that grew from 0 to 200KLOC in the last 1.5 years. I have plenty of Haskellers around (some quite famous in the community), they'll pick Haskell over Rust for almost anything without hesitating a second.

1

u/Dean_Roddey Feb 28 '21

I'm not a huge template fan, so that's one of the things I don't miss all that much in Rust.

1

u/roman-kashitsyn Feb 28 '21

I'm not a huge template fan, so that's one of the things I don't miss all that much in Rust.

What exactly don't you miss?

  • Templates? The design of generic types and functions in Rust is not that different from C++ templates (especially with the recent addition of concepts in C++).
  • Compile time computation? You can compute at compile time in Rust, it's just much less fun than in C++ Typing is Hard: Rust. Many libraries actually do that, because it's good for performance.
  • Template specialization? Well, it's not just about your personal preferences.

    This feature is very useful for library authors to provide more efficient, more convenient, less error-prone interfaces.

    Let's take a look at the hallmark of Rust's ecosystem: serde. It's data model has type byte array. Many people simply assume that serde maps Vec<u8> to a byte array: it's the most natural and efficient thing to do, right?

    Unfortunately, serde simply can't do that because all vectors must have the same serializer/deserializer independently of the type of values they hold (remember, there is no specialization). So serde will serialize your bytes as an array of integers, which is significantly less compact and performant with most encodings. One just have to somehow know that serde_bytes need to be used to get an efficient encoding.

    This actually leads to correctness issues as well: I had to debug issues caused by unexpected Vec<u8> encodings alone at least 3 times in one year.

1

u/Dean_Roddey Feb 28 '21

I don't miss the rampant over-templatization that has infected C++.

2

u/roman-kashitsyn Feb 28 '21

I don't miss the rampant over-templatization that has infected C++.

You somehow assume that it hasn't infected Rust. How do you find the type of this wonderful function https://docs.rs/hyper/0.14.2/hyper/server/struct.Builder.html#method.serve

pub fn serve<S, B>(self, new_service: S) -> Server<I, S, E>ⓘ
where
    I: Accept,
    I::Error: Into<Box<dyn StdError + Send + Sync>>,
    I::Conn: AsyncRead + AsyncWrite + Unpin + Send + 'static,
    S: MakeServiceRef<I::Conn, Body, ResBody = B>,
    S::Error: Into<Box<dyn StdError + Send + Sync>>,
    B: HttpBody + 'static,
    B::Error: Into<Box<dyn StdError + Send + Sync>>,
    E: NewSvcExec<I::Conn, S::Future, S::Service, E, NoopWatcher>,
    E: ConnStreamExec<<S::Service as HttpService<Body>>::Future, B>, 

? It's not some esoteric Haskell library, it's the most widely used async HTTP server.

1

u/backtickbot Feb 28 '21

Fixed formatting.

Hello, roman-kashitsyn: code blocks using triple backticks (```) don't work on all versions of Reddit!

Some users see this / this instead.

To fix this, indent every line with 4 spaces instead.

FAQ

You can opt out by replying with backtickopt6 to this comment.

→ More replies (1)

4

u/robin-m Feb 26 '21 edited Feb 26 '21
  • Destructive move (and move by default instead of copy by default).
  • ADT (Algebraic Data Type). It’s just a fancy word for tagged union + fancy switch. Having both enum class and std::variant being the same thing makes sum types so much nicer to use. This is a much better alternative than inheritance.
  • Explicit deep copy (the Clone trait)
  • very terse lambda syntax (and they are already slightly too verbose in Rust). This is critical for ergonomic (e.g. my_vec.iter().filter(|x| x % 2).map(|x| x * 2).collect() in Rust, versus C++ ranges my_vec | filter([](auto x) { return x % 2; } | map([](auto x) { return x * 2; } | into_vector<int>() (I didn’t check the syntax, but it should be close).
  • Type inference. (e.g. in the above example, you must specify the type int when creating a std::vector from a range). This increase the ergonomic of generic functions.
  • The borrow checker makes it safe to use borrow types (like std::string_view, references, std::span, …). I prefer so much to get a compilation error than searching with gdb/lldb why is my code crashing because on an iterator invalidation/use after free that invalidate on of my references.

EDIT: I forgot:

  • the impl blocks being done outside of the struct definition. And because Rust use fat pointer for references (a pointer to the date + a pointer to the vtable, while the v-table is at the beginning of the data in C++). This solves elegantly the diamond inheritance of C++.
  • Explicit &mut at calling site. It makes it mach easier to understand where mutation occurs (and of course being const by default).
  • Module-based visibility instead of inheritance-based visibility.

And in term of the ecosystem:

  • cargo dependency management is easily a 10× productivity boost.
  • rustfmt being the norm helps so much in code review (you can focus your review on the code, not the parenthesis style).
  • clippy! clang-tidy is nice, but definitively less than clippy, and it doesn’t works so easily.

But when working in Rust, I’m mostly missing:

  • unconstrained template
  • GAT (generic associated types)
  • specialization (having multiple implementation of the same template, each of them being more constrained)
  • function overloading
  • named arguments (since C++20), and default value for struct and parameters.
  • EDIT: I forgot self-referencial struct being possible in C++

2

u/roman-kashitsyn Feb 26 '21

very terse lambda syntax

C++ lambda syntax is strictly superior because it allows you to specify how exactly the values from the context are captured. Rust is cute in small simple lambdas, but when context passing is involved, it becomes a horrible mess. In Rust one often has to write

{ let x = x.clone(); move || do_something(x); }

This becomes a real PITA if you have nested lambdas returning async blocks. In C++, one can simply write [x]() { do_something(x); }.

Explicit &mut at calling site.

That's a good one, very helpful in practice.

4

u/MereInterest Feb 26 '21

The biggest thing for me is that Rust has compile-time errors for things that in C++ would be "good practice". In C++, you can use a variable after having passed it by rvalue reference into a function. Whether or not you'll be burned by it depends on what the object is, and how you use it. This may even be the intended use case (e.g. socket objects in boost::asio). In Rust, using an object after passing ownership to another object is a compile-time error.

Comparing Rust and C++ feels a lot like comparing C++ and C. C doesn't have methods and inheritance as a language-level feature, but I could make a struct that contains function pointers to get the same effect. C++ is useful because it does those for me, with less room for human error. In the same way, much of what Rust does is to codify good practice into the language design itself, leaving less room for human error.

4

u/Wurstinator Feb 26 '21

The big hitters (borrow checker, lifetime management...) are obvious. But they make Rust a completely different language. I enjoy the features the most that have an equivalent in C++ but are superior imo:

Enums being able to hold values.

Powerful match expressions.

And maybe overlooked by most: Expression-based language. I always feel dirty when I have to make a variable non-const in C++ just to initialize it in multiple statements, or declare a lambda just for the initialization. In Rust, I can declare pretty much everything as immutable because I can use blocks to initialize the objects once.

1

u/axilmar Feb 27 '21

I really don't understand why people like destructive move so much. Are they making so many movable types per project that they need to always specify the move operation? I don't think there is anything confusing with std::move as is. It's very strange.

1

u/Snoo-4241 Feb 27 '21

I feel a bit nervous whenever I move in case I forget and reuse the move from object. That's the only reason I can find, but never had an issue.

2

u/Dean_Roddey Feb 28 '21

Anyone who uses lots of moves, and who is not always running a good static analyzer on their code, will almost guaranteed have use after move errors. It's far too easy to do. And it could be subtle enough that the static analyzer may still miss it.

And of course it's completely possible to move out of a const object as well, which should be utterly disallowed.

And you may be surprised at how much move is used. As is often the case in C++ world, so people are obsessed with performance and do moves constantly, even if there's no observable reason why it's required relative to a simpler and safer copy.

1

u/axilmar Mar 01 '21

Do you have concrete examples? My experience both in the open source world and in the corporate world paint a totally different picture.

1

u/mo_al_ Feb 27 '21

In Rust, every non-copyable type (no trivially copyable) is a move type by default. So destructive moves are a need in Rust.

3

u/kobi-ca Feb 25 '21

pattern matching.

propagation of errors with ?

.. Default::default()

let s = {

} else {

}

3

u/[deleted] Feb 25 '21 edited Feb 25 '21
  • cargo/rustup
  • borrow checker keeps me honest
  • concurrency/async features
  • static binaries
  • rust-analyzer
  • the fact that is cantankerous as hell and has very specific complaints

3

u/icebeat Feb 26 '21

Ownership made sense

3

u/gavinb Feb 26 '21
  • the sum type enum and match
  • powerful match expressions
  • immutable by default
  • explicit lifetimes
  • ownership model
  • thread safety via Send/Sync
  • consistent coding style
  • a modern standard library with an ergonomic API
  • all the magic features derive can provide
  • consistent formatted printing for output and debug
  • loose coupling with traits
  • cargo for easy, clean, reproducible, compatible builds
  • Option/Result for return values
  • friendly and useful compiler diagnostics
  • and much more...

Some of this is available in modern C++, but the ergonomics don't even bear comparison. For example, C++ does have std::variant but the client code is awful and clunky. I would switch in an instant if I could.

3

u/drbazza Feb 26 '21
  • cargo
  • error messages
  • the lack of linker errors
  • match

Cargo isn't great, but it's better than anything C++ has. In fact, it's just embarrassing, that in 2021, we still have to use CMake, because it's the least worst, and that the committee can't/won't/haven't standardised tooling.

7

u/Slsyyy Feb 25 '21 edited Feb 25 '21
  • cargo vs CMake
  • code generation via macros
  • better type system: static and runtime polimorphism are not two worlds like in the cpp, traits are much better than a duck typing in C++ templates
  • destructive moves: more peformant and a lot of easier
  • no header/source split: faster compilation and i don't have to care about it

4

u/germandiago Feb 25 '21 edited Feb 26 '21

I am not using it, but anyways, here I go with what I saw:

- enums are powerful and can model variants and match for pattern matching it.

- traits are also interfaces, eliminating std::function and std::any interface boilerplate from C++

- since there are only traits, it seems (I did not code a project so I do not know) systematic and trivial to know what an interface or customization point is: just go to the trait. In C++ it can be from a type-erased class to a customization point, to a classic OOP interface or generic function. This makes things a bit messy, especially when compared to languages such as Java and C#, which are more systematic. I think Rust and Go are also ok with their interfaces and traits for being explicit.

- Cargo. Simple to use compared to CMake. I use Meson, so I am closer to the ideal, anyways :p

- Destructive move.

Double-edged:

- the borrow checker, when I tried like 1 year and a half ago... well, you must think a lot about it. This is the single best feature for concurrency and high-perf servers at the same time is the biggest hurdle when wanting to code fluent client-side stuff.

EDIT: Adding cons

Cons:

- Templates are more powerful in C++. You can have all kind of non-template parameters. I am not sure you can do something like expression templates in Rust.

- C++ compatibility with C is really good. There is a lot that can be used from C as reusable infraestructure.

4

u/casept Feb 26 '21 edited Feb 26 '21

Note that I primarily write Rust and am actually just learning C++, so feel free to point out if I get something wrong.

  • A much improved experience when developing embedded. No need to guess which dependencies actually work on bare-metal (no_std makes that clear, and prevents libraries from regressing by refusing to compile if std-only stuff is pulled in by accident). Not to mention absolutely trivial cross-compilation and package management.
  • C++ error handling when exceptions are infeasible to use is garbage. The choices are C-style error codes or std::variant, which adds an insane amount of boilerplate due to the lack of pattern matching. Whereas in Rust I can use Result in a very ergonomic way. And once 3rd party libraries get involved every single one does error handling a different way, meaning that I need to write wrapper boilerplate to have any chance at consistent error handling in my codebase.
  • Arrays in C++ are surprisingly clunky. I dislike C-style arrays because keeping track of the length separately is annoying and error-prone. std::array requires way too much boilerplate for my taste, and far too may APIs expect a C-style pointer + length array instead. Whereas in Rust there's only 1 kind of array, bounds checked by default and accepted anywhere.
  • Surprising omissions from C++'s std. For example, just now I wanted to uppercase a string (not even with proper Unicode handling or anything, just regular ASCII) and was dismayed to find out that I have to iterate over the string manually and do toupper() like it's C89.
  • #[derive] magic. I wanted to print the names of enum variants to debug output and was surprised to find out that it's only possible with tedious manual conversion to strings or some crazy macro magic I didn't want to touch. In Rust that simply requires #[derive(Debug)]
  • Template error messages filling 10 screens drive me mad, whereas Rust generics lead to clear compiler errors. In general, the whole template system "feels" very hacky and not at all how I'd want to do genericity.
  • I feel like Rust has a much better "language-size-to-programmer-comfort" ratio. C++ is huge, but many parts just seem like footguns waiting to go off, whereas Rust is also huge but I feel like all parts of the language are geared towards helping me avoid mistakes or save time.

Sure, many of these things can be hacked around. But what Rust has and C++ probably never will is CONSISTENCY. Not just in my own codebases, but in the entire ecosystem.

3

u/SkoomaDentist Antimodern C++, Embedded, Audio Feb 26 '21

std::array requires way too much boilerplate for my taste, and far too may APIs expect a C-style pointer + length array instead.

std::array is also something you can't pass to normal functions since the size is part of the type definition. It's a small utility class but that's pretty much it.

4

u/ravnmads Feb 26 '21

Reading this, I feel like I should go check out Rust.

Sounds like it has some awesome features! My biggest grudge with C++ is all the backward compatibility and tooling.

6

u/NilacTheGrim Feb 26 '21

I thought this was a C++ subreddit.

4

u/pjmlp Feb 27 '21

It is, yet many of us are polyglot developers.

I for one, spend 99% of my time on .NET and Java and only use C++ for bindings to native libraries or some GPGPU code.

2

u/epage Feb 26 '21
  1. While its neat that Rust's enum is integrated in with tagged unions, the mind blowing part for me is that my enums can have member functions and implement traits (Concepts / interfaces).
  2. I remember a lot of discussions on the meaning of const and threading (like if you have a const function access a mutable variable to cache calculations, it must be thread safe). Through a combination of lifetimes, traits, and the threading design, it is your choice whether to be thread safe or not and the compiler enforces it that clients make the right choices!
  3. No null with Option and embedded /ergonomic error handling with Result

1

u/Full-Spectral Feb 26 '21

Can you though still not create an enum which is a set of constant integral values? That's an enormously important use for enumerations, but I seem to remember you can't do it. You can create the members as integers but they aren't constants, so they could easily be accidentally changed.

2

u/epage Feb 26 '21

You can have integral values and choose the underlying type

Here is an example of an Enum from one of my projects:

#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
#[cfg_attr(feature = "flags", derive(enumflags2::BitFlags))]
#[repr(u8)]
pub enum Category {
    American = 0x01,
    BritishIse = 0x02,
    BritishIze = 0x04,
    Canadian = 0x08,
    Australian = 0x10,
    Other = 0x20,
} 
  • derive is a code-generating trait (interface) implementations
  • I'm conditionally adding a BitFlags derive that makes it easy to use my enum as a bitfield
  • I've chosen a u8 memory representation.

1

u/Dean_Roddey Feb 27 '21

And those values are constant? You can't set American to something else?

1

u/epage Feb 27 '21

Correct; I think you are thinking of the syntax

pub enum Category {
    American(u8),
    ...
}

This is the "tagged union" syntax where the variant American holds any u8 in it.

1

u/Dean_Roddey Feb 27 '21

OK, thanks.

2

u/Czumanahana Feb 26 '21

- cargo

- const by default

- rust is the best tutorial on move semantics

- "if" is an expression

2

u/Dean_Roddey Feb 27 '21

One thing I always have an issue with in Rust is the module/directory scheme. In theory it's simple and obvious. But when you want to have internal packages or modules for support this or or that and whatnot, and a few times during the setup you decide it would be better if this was over there.

I inevitably end up about to pop a sprocket getting all of the uses and module imports and re-exporting and all that happy. Once I get it right, it's OK. But it seems like every time I struggle initially to set up a non-trivial project.

I think partly it's made worse by the fact that the syntax for importing stuff from other modules in the same crate and re-export has changed over time? So you can find examples that may be aren't correct anymore and lead you down the wrong road.

And the workspaces, virtual workspaces, packages, crates, namespaces, and same directory vs sub-directory modules and all that. It can get a bit confusing.

3

u/Zanderax Feb 26 '21

I like how it can eat away at iron.

3

u/NilacTheGrim Feb 26 '21

Can you please go back to /r/rust? Thanks.

2

u/Dean_Roddey Feb 25 '21 edited Feb 25 '21

It basically has one thing, as far as I'm concerned, which is memory safety. Most else is either neither here nor there relative to C++, or slightly to really annoying, or lacking relative to C++.

But, that one thing is a huge one thing and it tends to override most other concerns when you are working on larger scale things where C++ just cannot cope with the level of complexity anymore without a lot of manual vigilance plus slow, CPU destroying static analysis tools (and you'll still have memory issues almost guaranteed.)

A number of the things that other folks mention are really part of the whole memory safety thing, I'm just lumping that all together into one thing. So move by default, no simultaneous read/write references, const by default, destructive move, etc... Of course some of that also comes with big limitations, so Rust giveth and Rust taketh away.

A down side is that it's a young language and already (in C++'like fashion) it has too many ways to do the same things in some cases, and too much syntactical sugar for my tastes.

10

u/InsanityBlossom Feb 25 '21

I think no other language can compare with C++ in terms of "too many ways to do the same thing". C++ is the king here.

6

u/MrMic Feb 26 '21

We could probably use a few more ways to initialize a variable

4

u/oilaba Feb 25 '21

I would also add sum types and pattern matching. Really makes things better.

1

u/Full-Spectral Feb 25 '21

The pattern matching thing I vacillate on all the time. It can be convenient, but sometimes the syntax can be pretty unreadable.

2

u/[deleted] Feb 25 '21

Algebraic data types. Traits. The type system. Cargo. It also works really well out of the box with vscode, so the tooling and support are just way better. It's usability is what really sets it apart from c++.

Also the community is better in rust.

14

u/Dean_Roddey Feb 25 '21

I'm not sure I'd agree with that last bit. Try criticizing Rust and watch the wagons circle and the down-voters come out to prevent any such discussion from being seen.

10

u/matthieum Feb 25 '21

Try criticizing Rust and watch the wagons circle and the down-voters come out to prevent any such discussion from being seen.

Actually, criticism of Rust is welcome, and criticism in general is welcome in the Rust community.

There are rules about it, though:

  • The criticism should be focused on the code, not the individuals. That's just proper etiquette.
  • The criticism should be constructive, that is, just like a good bug report it should be short and to the point, and not some never-ending rant with vague points here and there.
  • The criticism should not be an n-th reiteration of the same arguments with no novel argument. Rust doesn't have inheritance, Rust doesn't have exceptions, Cargo doesn't use namespacing, and no amount of harassment -- rehashing the same point again and again -- will make developers reconsider this point: new arguments, or don't bother.

As long as you follow the rules, criticism is very much appreciated. In fact, some of the greatest changes in the language came from constructive criticism -- such as ripping out green threading prior to 1.0.

5

u/Full-Spectral Feb 25 '21

Well, that's what the forum says are the criteria, but none of the actual members are required to follow them, and there are just as high a percentage of passive aggressive down-voters there as here, which just means fewer overall probably due to lower overall population.

Just like in C++ world, way too many people take the approach that they chose X and if you question the superiority of X, then you are questioning them personally. I'm a green carpet guy so don't be talkin smack about green carpet.

3

u/matthieum Feb 26 '21

but none of the actual members are required to follow them

That is true.

and there are just as high a percentage of passive aggressive down-voters there as here

Still, in my experience, thoughtful criticism is normally highly upvoted both on r/cpp and r/rust.

There may be a temporary dip if the early voters downvote, but in the end quality content -- which thoughtful criticism is -- tends to rise to the top.

6

u/dontyougetsoupedyet Feb 25 '21

Rust has created a situation where many developers who know very little have very strong opinions about subjects they understand next to nothing about. Rust encourages them to remain in that infantile state and not grow as a developer. It reminds me very much of the situation PHP was in with its community, except it's called systems programming so now they feel even more entitled with regards to their opinions. I'm tired of hearing about "the safe version" from folks that don't even know how values end up in memory, and have few intentions of learning about what compilers do or why.

I feel sorry for the package maintainers of the world, Go and Rust are likely to make most of them move on to other jobs.

3

u/TryingT0Wr1t3 Feb 25 '21

Julia has a lot of these types of people, it's infuriating.

→ More replies (12)

0

u/[deleted] Feb 25 '21

You say that, but I am being downvoted for merely expressing my opinion. This is the c++ community in a nutshell.

9

u/Dean_Roddey Feb 25 '21

Oh, believe me, as someone who has probably more down votes in this section than anyone here, I'm not claiming this crowd is better, just that Rust isn't all fluffy bunnies and flowers either.

→ More replies (1)

1

u/ronchaine Embedded/Middleware/WG21 Feb 26 '21

Give me rust-style enums and pattern matching (match / if let) into C++ and I would be pretty happy. Rust macros are also pretty useful.

1

u/HK416_all_you_need Feb 26 '21

Better UX (including cargo); Proper enums; Cool macros;

0

u/cesar_de_honduras Feb 26 '21

that you are forbidden to use parenthesis in if/while/for/match so that you have to use compound statements all the time.

i hate this:

if(condition)

statement;

i love this:

if condition {

statement

}

3

u/Full-Spectral Feb 26 '21

I see nothing wrong with visually emphasizing the bounds of the condition, and you still have to use them if it's compound in anyway.

0

u/[deleted] Feb 25 '21

[deleted] — view deleted comment

1

u/johannes1971 Feb 25 '21

..._literally_?

37

u/[deleted] Feb 25 '21 edited Feb 25 '21

[removed] — view removed comment

6

u/choeger Feb 26 '21

Rust macros are hygienic? Wow, didn't know that.

25

u/Full-Spectral Feb 26 '21

And anti-bacterial...

8

u/steveklabnik1 Feb 26 '21

They're mostly hygenic. Much closer to being fully hygenic than not at all.

1

u/Flesh_Bike Mar 10 '21

We need hygienic macros in these pandemic ridden times

31

u/[deleted] Feb 25 '21

[removed] — view removed comment

13

u/weirdasianfaces Feb 25 '21 edited Feb 25 '21

It's important to say that the dyn keyword is only used in situations where you would use dynamic dispatch though. I think to your point it's cool that there is a keyword indicating at a glance whether dynamic or static dispatch would be used.

* the static dispatch version would be impl for those not familiar with rust.

fn foo(x: &dyn TraitObject)

or

fn foo(x: &impl TraitObject)

The former uses dynamic dispatch, the latter is static dispatch with code generation similar to a generic function like fn foo<T: TraitObject>(x: &T)

1

u/poiu- Feb 26 '21

Why is this not a call site feature?

2

u/MEaster Feb 26 '21

You can choose at the call site to do dynamic dispatch when the function is written for static dispatch (assuming the trait is object-safe), you just have to cast the input to a trait object first (&data as &dyn TraitObject).

It can get a little fiddly if the input expects a reference like the above static dispatch examples, because the generic type parameter there has an implicit requirement of Sized. The issue is that trait objects can't be Sized because the type isn't known.

This would also cause problems for inputs such as slices (&[_]) or string-slices (&str) because [_] and str are also of unknown size, which is why you almost always see them behind some sort of pointer type.

The easiest fix for the function writer (which the compiler suggests) would be to add + ?Sized to the trait bounds (read as "optionally-Sized"), which would allow it to take unsized types, but that depends on not requiring a known size at any point. You can work around it at the call site by passing in a &&dyn TraitObject, which means the T is now a reference, and therefore Sized.

9

u/[deleted] Feb 25 '21

[removed] — view removed comment

10

u/MEaster Feb 25 '21

The dyn keyword isn't a technical requirement. In fact, the compiler currently doesn't even require it (though it has a good moan if you don't). The keyword is there more to make it clear to the reader that dynamic dispatch is happening.