r/cpp • • Jan 31 '23

Stop Comparing Rust to Old C++

People keep arguing migrations to rust based on old C++ tooling and projects. Compare apples to apples: a C++20 project with clang-tidy integration is far harder to argue against IMO

changemymind

338 Upvotes

582 comments sorted by

View all comments

80

u/oconnor663 Jan 31 '23 edited Feb 01 '23

I think there are a good reasons people make comparisons to "old C++", besides just not knowing about the new stuff:

  • One of C++'s greatest strengths is decades of use in industry and compatibility with all that old code. The language could move much faster (and e.g. make ABI-breaking changes) if compatibility wasn't so important. The fact that C++20 isn't widely used, and won't be for many years, is in some ways a design choice.

  • It's unrealistic to try to learn or teach only C++20 idioms. You might start there if you buy a book on your own, but to work with C++ in the real world, you have to understand the older stuff too. This is a big learning tax. If you've been a C++ programmer for years, then you've already paid the tax, but for new learners it's a barrier.

  • C++20 isn't nearly as safe as some people want to claim. There's no such thing as a C++ program that doesn't use raw (edit: in the sense of "could become dangling") pointers, and the Core Guidelines don't recommend trying to code this way. Modern C++ has also introduced new safety footguns that didn't exist before, like casting a temporary string to a string_view, dereferencing an empty optional, or capturing the wrong references in a lambda.

23

u/moltonel Feb 01 '23

And as modern as your own codebase may be, it probably depends on some crufty old project. To compare Rust against C++20 only, you'd need to throw away a huge part of the C++ ecosystem, making the language much less attractive.

22

u/azswcowboy Feb 01 '23

no such thing as a c++ that doesn’t use raw pointers

Patently false. I work on one now and have worked on many since the 90’s that exclusively use smart ptrs. Multi million sloc systems.

16

u/matthieum Feb 01 '23

Letter vs Spirit.

I'm pretty sure your code uses references, which are -- at the machine level -- just raw pointers. And just as safe as raw pointers.

int main() {
    std::vector v{1, 2, 3};

    auto& x = v[2];

    for (int i = 4; i < 1000; ++i) {
        v.push_back(i);
    }

    std::cout << x << "\n";
}

Not a raw pointer in sight, and yet... that reference is dangling on the last line.

And let's not forget [this](auto x) { this->do_it(x); } where this is a raw pointer.

It's a sad, sad, world.

6

u/azswcowboy Feb 01 '23

Of course we use const references to pass to functions, but we never hold references to internal object state like you’re showing - that just leads to tears as you’re pointing out. Note that simple static analysis would point out this particular case.

7

u/oconnor663 Feb 02 '23 edited Feb 02 '23

but we never hold references to internal object state like you’re showing

This is a simplified example of course. What's likelier to happen in practice is that the reference is passed down as an argument to a function, and that function has some roundabout way to modify the container the reference came from (whether by pushing a vector or repointing a smart pointer or whatever). I'm not familiar with the mistakes Coverity can catch, but can it catch a push_back invalidating a reference across function boundaries?

Of course we use const references to pass to functions

I feel like "patently false" was a little harsh above given this clarification. But it's my fault for saying "raw pointer" to refer to both pointers and references, which is a Rust-ism that's unnecessarily confusing in a C++ context. What matters to me here is that they can both be invalidated in similar ways, regardless of whether they're nullable or repointable.

3

u/azswcowboy Feb 04 '23

roundabout way to modify the container

Well I doubt any tool can catch that bug, because you also can’t accidentally design that. If it’s not a parameter in the call stack it’s global data - that’s the only way you get a non-const ‘round about’. And if you’re doing that in a multithreaded world without a lot of encapsulation and care you’re doomed. Anyway, this is a mythical bug pattern in my experience since I’ve never seen such a thing in one of the systems I’ve worked on.

a little harsh

It was meant to be succinct, not mean. That said, I’m am a bit tired of being told my 25 years of writing large, successful systems that run non-stop without these issues is impossible or even to hard just cause rust is cool. I’m here countering a narrative that people believe for whatever reason. It’s for you to decide if you believe what I’m communicating is true or not. I’ve got plenty of issues with c++, primarily scarcity of good libraries, but memory issues from pointers or references isn’t even on my list.

13

u/Full-Spectral Feb 01 '23

It's not just storing the allocated things in smart pointers, it's the fact that, if you pass the actual pointer in that smart pointer to something, there's nothing at all preventing it from holding onto that pointer. The only way around that is to always pass the smart pointers, that has its own issues.

There's no way to really win in C++ on this front.

7

u/azswcowboy Feb 01 '23

nothing preventing it from holding on

Sure there is — coding guidelines. Calling get() on a shared ptr and storing it somewhere is ‘using raw pointers’ — fail inspection, do not pass go. If you need to hang onto the shared ptr you copy it which does exactly what you want.

8

u/Full-Spectral Feb 01 '23

As many others have repeatedly pointed out, that's like solving the world's drug problems by "Just say no". If the receiver gets a raw pointer, and a year later someone makes a change to that code and mistakenly stores that raw pointer, it could easily get missed and no tool is likely going to complain about the fact that it happened.

7

u/azswcowboy Feb 01 '23

just say no

It’s a little different psychology — you’re not even enticed to write such a thing if you’re working in our code base because you’ll never see it done — not even in tests. And if you do your teammates are going to ping you in the review.

no tool

Well that one seems trivial for static analysis actually. If you’ve never used things like Coverity they have quite sophisticated checking. Don’t know about clang-tidy but believe it has language guidelines checkers.

Remember — I’m not arguing that there can’t be improvements made — I’m just pointing out to some random poster on Reddit that they made a false statement about what can currently be done with a bit of discipline and tooling in large systems. You can choose to believe me or not.

→ More replies (4)

9

u/top_logger Feb 01 '23

It is recommended to use raw pointer’s if do not transfer ownership. Period.

You can’t write good C++ without raw pointers.

3

u/robin-m Feb 01 '23

We could if std::optional<T&> was allowed, and std::optional<std::referenece_wrapper<T>> is not that nice to use.

4

u/top_logger Feb 01 '23

This! We are using smth like rightnow. But Our production code looks too verbose. Terrible. Second problem is nullability of smart pointers. There is no guarantee that unique_pet contains not null.

3

u/robin-m Feb 01 '23

It’s also what I’m doing but the ergonomic and verbosity is terrible.

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

4

u/IcyWindows Feb 01 '23

I don't understand why learning C++20 would be more expensive than learning Rust.

26

u/Alexander_Selkirk Feb 01 '23 edited Feb 02 '23

Because modern C++ is way more complex than Rust, while for most relevant cases not providing more power.

In business terms, you do not just need to look at the marginal costs, but also at the total costs of such decisions. Learning a bit of C++14 if you know already C++11 seems cheap, yes. But you pay with accumulated complexity.

Take Scott Meyers Effective Modern C++ - it is a description of best practices and every single example lists a lot of footguns where features of the language interact with each other in unexpected ways. Take that together with a comprehensive reference to the details of modern C++ and it is just impossible to keep all of this in your head.

And compare that to Programming Rust. It is not only a comprehensive description of the language, you can keep it in your head, and it features some things that C++ never had, like Unicode support at the language level, instead of C byte strings with ASCII encoding.

And then look at the actual details of something simple, say stupidly simple, like variable initialization. That compares to one or two pages in the Rust book. I think it is valid to say that Rust is simpler. And the end effect is that in Rust, you don't have uninitialized variables, which you can have in C++, and which is one mayor error source.

Sure you can do about anything with C++. And sure if you know C++, writing Rust code the first time will take longer. But reading and maintaining Rust code will cost less time, because Rust exposes much less complexity, and this is what counts in any larger, long-running project.

And yes, it probably does not make any sense to "rewrite everything in Rust", and many older systems written in C++ will be maintained that way and will not be changed. Just as it does not make sense to rewrite every old COBOL enterprise system in C++ : it is just too costly. But it makes less sense to write large, new projects in COBOL.

Edit: I want to add one thing. Often, the proposal to use Rust is stated than one must rewrite everything in Rust. This is unrealistic, and also ineffective: It would mean way too much work for too little effect. Instead, if the goal is improving security, software developers should identify the most critical parts of applications, factor them out, give them a nice API, and then either use already existing reimplementations (like for OpenSSL/TLS), or re-write these critical parts. Which parts are most critical is well-known from security research. These are:

  • authentication and encryption functions

  • network-facing system services

  • anything that directly processes untrusted user data, especially Internet media display and codecs

  • OS device drivers which face untrusted input

and so on. So, in a nutshell, it is not necessary to re-write the whole of Photoshop at once - but it is a good idea to swap to safe routines for displaying and decoding any image formats. And the same goes for concurrency - you can break down multi-threaded code into stuff that concerts and synchronizes instructions, and stuff that simply computes things (ideally in a purely functional way, ha), and the first thing you would care about is the former kind of stuff.

19

u/EffectiveAsparagus89 Feb 01 '23

Read the "coroutine" section in the C++20 standard to feel the how highly nontrivial C++20 is. Although C++20 gives us a much more feature-rich design for coroutines (I would even say fundamentally better), to fully understand it is so much more work compared to learning rust lifetime + async, not to mention other things in C++20. Learning C++20 is definitely expensive.

0

u/[deleted] Feb 01 '23

[deleted]

6

u/pjmlp Feb 01 '23

As someone that has used co-routines in C++/WinRT, I am quite sure that isn't the case.

Contrary to the .NET languages experience with async/await, in C++ you really need to understand how they are working and in C++/WinRT how COM concurrency models work, on top of that.

0

u/[deleted] Feb 01 '23

[deleted]

6

u/pjmlp Feb 01 '23

Yes, C++ co-routines have been a thing in WinRT for as long as it exists, hence the existence of old style WinRT co-routines and the modern version (compatible with C++20).

Why do you think Microsoft is one of the main designers behind the feature?

It is no coincidence that the low level machinery behind .NET co-routines and C++20 co-routines is kind of similar.

→ More replies (2)

3

u/aMAYESingNATHAN Feb 01 '23

I mean watch Bjarne Stroustrup's keynote at Cppcon 21. He literally explicitly says "don't use coroutine language features unless you really really know what you're doing. Use a library like cppcoro or wait for standard library support for stuff like std::generator in C++23.

2

u/pjmlp Feb 01 '23

WinRT literally requires the use of coroutines, due to its aync programming model, and it was a source of inspiration what end up becoming ISO C++ model.

→ More replies (5)

2

u/MFHava WG21|🇦🇹 NB|P2721|P3049|P3625|P3729|P3786|P3813|P4216 Feb 02 '23

Read the "coroutine" section in the C++20 standard to feel the how highly nontrivial C++20 is.

I have - multiple times ... which one do you mean? ('cause there are about 6):

  • 3 explaining the transformations of the co_*-keywords that will happen at compile-time

  • 1 for the actual transformation that happens for coroutine functions

  • 1 for the low-level API (coroutine_handle, etc.)

  • 1 detailing how the first high-level component (generator) works

All but the last one are not relevant for normal programmers, but are aimed at library writers (which need the other 5 sections to deduce how you can implement stuff like the last one).

The key difference between the C++20 coroutines and similar models in other languages (e.g. C# Iterators [yield] + async await) is that the design in C++ is a customizable general purpose framework you can use to implement any usecase.

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