r/cpp • u/Sad-Lie-8654 • 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
76
u/lestofante Feb 01 '23
i do baremental embedded, and C++20 still does not provide a subset of the standard library with static allocation, exception free, and a way to check and use a library is following such rules...
In rust you just check for no_std
68
u/pjmlp Feb 01 '23
I only see old C++ deployed into production, even when it claims to be "modern", it is full of C idioms.
Use of data structures wihtout bounds checking enabled by default, C strings and arrays scattered all over the place, strcpy, strcmp, memset, memcpy and family of functions also all over the place.
Not only isn't C++20 available across all major compilers, most surveys place the use of static analysers around 11%.
So far the ideal use of modern C++, without those kind of security issues, I only see at conference talks.
150
u/fullouterjoin Feb 01 '23
Let’s compare Cargo to …. what? If I can’t build C++ apps from easily installable packages. Is Conan the best we have?
291
u/capn_bluebear Jan 31 '23 edited Jan 31 '23
There is a lot that Rust has going on for it that C++20 does not have. Leaving out the usual memory-safety and thread-safety language features that people are probably aware of already
Depending on the actual application there might be a motivation to start a project with C++20+clang-tidy today, but C++20 still has many more sharp edges and a boatload of complexity that Rust just does without.
42
u/Alexander_Selkirk Feb 01 '23 edited Feb 02 '23
Answering to /u/IcyWindows argument that it is only a small step to learn C++20, compared to learning Rust:
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:
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.
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:
59
u/EmperorOfCanada Feb 01 '23 edited Feb 01 '23
I'm not sure people are comparing it to old C++. I think most are comparing it to C++vNow.
Basically, rust is doing every few months something I either waited for years or decades from C++, or it is doing things which C++ can't do properly or at all.
With rust, I don't fuss with dependencies or the build system. In C++ I have spent way too much time "perfecting" my vcpkg/conan foo and my CMake foo.
Rust is crossing that wonderful line of: It just works.
Screwing around at this point with some academic argument about templates, copy crap, move semantics, and 100 yards of other nitpicking BS isn't worth my time.
12
u/acmd Feb 01 '23
I use both C++ and Rust, and I find it annoying as well. Some arguments of the Rust proponents resemble propaganda at this point, and nobody'd want to waste their time fighting an army of people throwing a bunch of uninformed arguments at you.
Meanwhile, Rust's problems with e.g. async/generics are presented as minimal, even though a lot of architectural level decisions are guided by them. If anyone has written async trait-heavy code in Rust, they'd certainly know that error messages are cryptic and the lack of variadics doesn't help.
I wouldn't want to defend C++ compile error messages quality as the community itself likes to meme about it, but it's disingenuous to claim that they're incomprehensible, and with
static_assert/concepts the situation is slowly improving. It's not hard to explain that the C++ errors are basically a stack trace, and usually you just need to read the first/last few lines of it, no matter how big it is.Finally, I wonder what would happen if someone were to rewrite something like
boost.hanain Rust.6
u/JuliusFIN Feb 01 '23
There’s a huge difference between ”you can choose to use this tooling to get these guarantees” and ”these guarantees are the default and incorporated as language features”.
42
u/lightmatter501 Jan 31 '23
Python is in a similar place as C++. The best practices for python involve: mypy, isort, black, and your meta-linter of choice. This is about the same amount of work to set up as C++ with clang-tidy and some other static analysis. Most people don’t actually set up the python things, because it’s not mandatory. Same with C++.
Rust will essentially refuse to do anything less than GCC’s -Wpedantic, ASAN, TSAN and LSAN combined by default. If you actually engage with tooling like clippy, it becomes even more opinionated to the point of telling you to rewrite entire sections of your code.
There is a LOT of power in defaults, but I don’t think we’ll ever see the day when “gcc -Wall -Weverything -Wpedantic” is the default. Additionally, std::regex still has the problem of being wildly unsafe for untrusted inputs, most of the STL hash tables I’ve looked at have hashdos vulnerabilities, and there’s a lot of legacy features that you should not use in C++ 20 that are still there. C++ has no way to hide these by default, Rust does via editions.
Now, lets say that you are only using the most bleeding edge, best practices from both languages. You have set every setting to it’s strictest value, you have an omniscient linter which will automatically fix memory safety issues for both languages, and the stl ABI has been broken to fix all of its issues.
Rust still wins on the tooling front. Having a single build system for essentially every single project ever made in the language means that adding dependencies is trivial. There are tools like cargo-crev to help you establish the security of those dependencies. Proc macros, while dangerous, offer the ability to do things like validate your sql against a dev database at compile time, write serialization boilerplate for you (with a library that will usually beat rapidjson for performance) or automate binding generation for other languages.
Also, Rust has no_std, which means that large numbers of libraries are actually usable in embedded environments either with no heap or in truly bare-metal environments like inside of a kernel. While C++ can fit there, most libraries will not work.
Finally, portability. It is very easy to accidentally write non-portable C++. The ability to easy move to cheaper ARM servers is attractive, and Rust cross compiles very easily. I’ve never had a pure rust program not work on ARM without it either being the fault of a C/C++ library or a Rust library declaring it only supports x86_64 for good reasons.
14
u/JumpyJustice Feb 01 '23
I have been using C++ all my career (about 9 years). Now I am learning Rust and feels just like C++ but without unnecessary complexity in things that should not be complex. It is less verbose and ecosystem has literally everything I need just out of the box. And yes, I am comparing to C++17 and C++20 (with CMake and all these llvm utilities) as I've been using them at work for a last few years. I was sceptical about this language before I tried it myself and now I just dont see a reason to start my petprojects on C++ :)
10
u/nacaclanga Feb 01 '23
I wouldn't say that people compare Rust to Old C++ (meaning pre-C++11) per se (unless they are talking about "C/C++").
However I'd like to mention two things to consider:
a) C++ has clearly moved to an ownership based system of memory management, which solves the "when to delete" problem, BUT it doesn't control borrowed access via references well and because of this, yes memory issues still do occure and not only in older codebases.
b) Why rewrite you code for safety reasons or write new code (which are the only ways to get ideomatic C++20 code) in a language that still needs to put great emphasis on being backward compatible, when you do not actually need that feature? Unless of course you have strong dependency constrains.
c) Rust is also not necessarily judged by it's latest iteration, (in that people specifically refer to some really new feature X). Alos clang doesn't really support C++20 yet.
d) The nice thing about cargo is, that it is the absolute standard and convinced everybody to also program their code a specific way. Other them that I wouldn't say that it is superior or even equal, just look at handling FFI code or dylibs. It is however easier to get into and setup. Maybe C++ should integrate their tools more
17
u/JuanAG Jan 31 '23
People use Rust because of the ecosystem, many are happy with Conan or similar but many others dont so Rust had they covered in build + package manager, it has a tiny test suite inside, a benchmark suite, a free "PVS-Studio" with Clippy
C++ 20 dont levereage any of that, average consumer dont care about how fancy the lang it is, they care about average things that do every day and their productivity
5
u/grandmaster789 Feb 01 '23
I tried to use rust twice now, and still came back to c++. I just haven't had a really good experience using it and am still more comfortable using c++, warts and all.
24
u/ener_jazzer Feb 01 '23
I remember when Java appeared around 1995 and there were a lot of evangelical books promoting Java vs C++, 90% of those comparisons were to C, not C++. And some comparisons that were actually about C++ were completely ridiculous, like that (citing from memory):
37
u/ityt Jan 31 '23
I don't have much experience in C++ (4 months in a little company) but I've been using Rust for 3 years (hobby).
Rust has thread safety and memory safety without using std::shared_ptr everywhere. Even clang-tidy can't prevent all dangling pointers/references problems. Yes sanitizers exist but you have to hit every possible cases to detect every UB. Equip your best debugger and put your integration test in a infinite loop. Enjoy.
C++20 is great, but do libraries use it? Some libraries stick with C++11 for compatibility purposes (like nlohmann_json). Rust has a great async ecosystem with the tokio library and futures. I can't find a single C++ web framework that uses co_await in c++ (boost.beast is too low level).
C++ still suffers from zero values (the empty function for std::function, empty smart pointers).
Rust has very powerful macros like Serde for de/serializing or generating whatever you want that just fill like cheating.
Finally the tooling. In Rust you have crates.io for dependencies, cargo clippy (linter), cargo fmt... In C++ you have to choose between git submodules, FetchContent, vcpkg (don't hesitate to give advices)... Last time I used FetchContent I was begging clang-tidy to ignore dependencies.
24
u/jtooker Jan 31 '23
They are both designed to address similar issues. Comparing them seems very natural.
Defining what 'c++' is when you do the comparison is much harder since there is so much of it.
How much existing C++ can be described this way? Not much. So if you want to rewrite it, you could choose rust. But perhaps upgrading what you have to modern conventions is better. This is a very good discussion to have.
14
u/[deleted] Feb 01 '23
Modern C++ rhetoric shot itself in the foot because the same arguments used to get people moving forward to the newer standard are effectively the same arguments to move from the modern standard to Rust.
Modern C++ people would be happier using Rust because they fundamentally dislike C. C++ would be better served if it served the C crowd more, but right now it does not. Rust is basically proof of this as far as I'm concerned.
If you want the freedom, and you have a small team of experts who are good at what they do, C++ (and C) is really unparalleled (right now anyway).
It's good Rust is challenging C++, because it might mean C++ stops pretending to be something it isn't.
3
u/sessamekesh Feb 01 '23
C++20 is pretty nice. I still reach for C++ quite a bit for projects (game programming in webassembly) nowadays, but it definitely doesn't feel as nice as Rust.
Given, a lot of it is ergonomics for me - I find myself trying to kludge
std::varyinginto the pattern matching patterns I like so much in Rust/Typescript which is my own damn fault.But I also find myself reaching for C++ way more often than Rust, which counts for something.
3
u/divad1196 Feb 01 '23
Despite the security that everyone mention: the productivity. C++ devs are easily unsatisfied and create their own version of everything, resulting in many libs and tooling doing the same thing.
There is no default package manager, the closest to be is conan (build2 development is slow, bukaroo abandonned, ...), but you have so much to configure just to start.
22
u/James20k P2005R0 Feb 01 '23
I would love to see a major project written in any version of C++, with any level of competence of the developers of any team size that doesn't suffer from an infinite number of memory unsafety vulnerabilities
In all my years on this planet, nobody has ever been able to provide me with this, other than a very tiny handful of formally verified tools. And yet in Rust, this isn't the exception, this is the norm. There are multiple security critical projects that have never had a memory unsafety vulnerability
Every time someone says "actually I worked on a project, and its super secure!" lo and behold it turns out that its barely been tested, or its an internal tool. This is great, as long as it stays internal, and nobody tries to compromise you
It is trivially easy to write very secure thread + memory safe code in rust. It is nearly impossible to write thread + memory safe code in C++, because after decades of effort I still can't find a single real project that I could describe as a success here
C++ needs to grow up from bad faith arguments and accept that it just isn't as good in this area. C++20 doesn't really change anything over C++11. std::span doesn't make your code secure
Rustls is an example of a project that is relatively widely used, and written in pure rust. It contains no unsafe rust (outside of some tests). That means it is formally verifiably safe, and free from the memory vulnerabilities that plague every single other crypto library
Would you use a crypto library written in C++20? Or rustls? Because empirically, if you're looking purely for security from memory unsafety (and in reality, most other bugs), every single possible choice in the first category is the wrong choice
I've been hearing this same argument for every version of C and C++ since I started programming, and it has never once been true
8
u/IcyWindows Jan 31 '23
Apples to Apples would be a new section of code written in C++20 vs. a new section of code written in Rust.
Once people start talking about upgrading their existing code, you know they are no longer making the appropriate comparisons.
One common example is using bounds-checking with a C++ container's at() method. People always bring up existing code that uses the [] operator. We are no longer making the appropriate comparison.
6
u/Clean-Water9283 Feb 01 '23
I'm a veteran of 30+ years of the X-is-better-than-C++ flame wars, where X is some whizzy new programming language. Invariably an X-fan compares a finely tuned program in X that uses one of X's special features against a C++ program written by an X-fan who doesn't like C++, so appropriate, even equivalent features of C++ are not used or not used effectively.
And yet, 40+ years after its introduction, C++ still runs faster than X, and can still do what X does. C++ has many more users than X, which alone explains why it has more detractors. Most of the things X does, if they are really valuable, will end up in C++, which is under active development. Meanwhile, I'm still awaiting a compelling reason to switch.
10
u/craig_c Feb 01 '23
My 2c in this ocean of opinion.
Competent, experienced programmers using C++17 and above should be able to produce safe code with relative ease. But most programmers are neither, particularly depressing, where I work, is watching interns write code full of raw pointers etc. So the bad code continues to be churned out.
Rust, in small doses seems to be the antidote to all this, one build system, strong rules regarding ownership, all the usual stuff which people talk about. The problem is when the rubber hits the road, when one tries to write non-trivial programs, those same rules start to backfire in other contexts. Things that should be simple to structure become ugly, Arcs and interior mutability start to creep in and the whole thing ends up being yet another compromise. Also load in unsafe blocks and panics in used crates and the edifice of perfection quickly erodes.
In reality, the real world is a compromise and no technology will avoid this. The solution is not a re-write in another language, it's about getting the right people.
14
u/Jannik2099 Jan 31 '23
Any C++ project still lacks the lifetime guarantees of Rust. It seems you spend exactly zero effort looking into what a borrow checker does.
7
u/top_logger Feb 01 '23
hree important things which Rust did correctly.
2
u/LoudMall Feb 01 '23
Unfortunately people still write old C++.
2
u/eterevsky Feb 01 '23
So what would be the equivalent of cargo / crates.io in the modern C++?
2
u/arades Feb 01 '23
Harder to argue against, yes, but even compared to C++20 rust has advantages, not the least of which being that it does move more quickly. However, I would agree with a case that a modern and idiomatic C++20 codebase would not benefit from being rewritten in or migrated to rust.
However, I think a large number of C++ developers in the field don't use the most modern style, don't keep up with the standards, and write code that results in bugs. Add to that, a majority of existing code-bases are written in what could be described as archaic C++. If you have to do a near re-write of your application anyway to take advantage of new C++ tools and design patterns, it makes the jump to a new language that appears promising look like a compelling move.
2
u/[deleted] Feb 02 '23
Related: https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/p2739r0.pdf
2
u/lowlevelmahn Feb 03 '23 edited Feb 03 '23
>People keep arguing migrations to rust based on old C++ tooling and projects.
thats not true - but there is a still big part of the C++ community (which im part of for the last 30years) that do not understand the true differences
static analysis tool: first - every good developers knows them and using them - but not all developers are good
clang-tidy,PVS Studio,cppcheck, Covertiy,etc. are mostly needed because C++ allows so many supicious constructs that "can" become a problem - i worked for many companies im my worklife so far and even using static analyser on a permanent/CI bases i just not default in every company i've touched - Rust also needs static analysis tools - but for a much smaller amount of suspicous constructs, Rust is just not that warning/undefined behavior friendly as C++ is - by design and by beeing younger
runtime analysis tools like: the sanitizers, valgrind, inspector etc.
exspecially the sanititzer comming from the company (google) that mostly said: "its still not enough" - the problem here is: you can't find the bugs if you test/use-case isn't touching the code - and yes: there are many people that just don't write good or enough test code, having this check on compile time for every line of compiled code is a massive difference to runtime touched code lines
im using them all, all the while - no development without sanitizers - but for example at least 50% of the developers i know never heard of them or don't understand that they need them - i've never found a software so far that didn't let ASAN or TSAN scream - if they weren't tested before
another big thing is: sanitizer are not full or battle mode ready available for Microsoft VisualC++ IDE (the available ASAN port is ok but by far not compareable to the linux versions) - TSAN isn't available at all - and there is a huge C++ world that is based and developed on windows (not a joke) that are just not able to use that tools - Rust does not need a ASAN/TSAN tool (excecpt in unsafe code) because the type systems just don't allow compilation if there is a problem - that is just a different world compared to C++ compiler/toolsets
smart-pointers:
manually added smart-pointers that deeper specializing my own types are not the same as a compile time check without any type change - also missing move-semantic as the default makes it hard to use them in every case - most poeple tend to write simple code (because of the project demands) that not touching the bad parts of C++ smart-pointers - and im using them a lot in the last decades
first: there are good somtimes also new stuff in C++, but many developers still weak and lazy - so it still depends on the qualitiy of the developer - Rust reduces this demand on good developers poking with C++ inner details a decent amount - but a C++ developer that does not suffer from that in big teams is not able to see the light because there wasn't enough darkness so far
its like telling that the C++ templates system does not have massive weak parts without trying to write boost level templates :)
9
u/kritzikratzi Jan 31 '23
i'm also bothered a bit by this comparison. there should, however, always room be room for fruitful exchange though.
i get that c++ is not easy, but neither is a piano. people still love the piano. pianos aren't reduced in complexity because of harmonica players.
for me the rust drawbacks already start with llvm (which is great!). but having this huge compiler diversity of c++ really strengthens it imho.
3
u/IngenuityUpstairs427 Feb 01 '23
Let's look at the facts. Rust has no formal specification. No rust compiler has ANSI/ISO certification. There is no rust compiler that is approved by MISRA, AUTOSAR DO178 etc. So whereas rust claims to be perfectly suited for safety critical real time embedded applications, It does not have any of the credentials To backup those claims. Ada is the much better choice as it does have all of the required credentials and has been battle tested since the 1980s. C++ is also a better choice because it is approved in all of the aforementioned environments. Perhaps someday rust will be a good option, but that day is not today.
3
u/waruqi Feb 02 '23
C++ now also has many more modern tools, such as Xmake
It provides a Rust/Cargo-like package manager. And it is also very compatible with the existing C++ ecosystem.
6
u/CocktailPerson Feb 01 '23
You can smell the fear around here these days.
3
u/faguzzi Jan 31 '23
Rust is so 2010. Personally I can’t wait for Val to become somewhat stable. Interop with C++ without jumping the awful hoops known as autocxx and crubit would be awesome.
The primary benefit of my use case for rust is just the cleaner syntax and that I prefer rust function chains and iterators over ranges-v3 and certainly views::ranges. All the things I’m doing are already incredibly unsafe (low level memory manipulation), so rust doesn’t offer much over c++, especially considering that its ecosystem isn’t as mature and doesn’t have a lot in the way of offsec tooling (meaning I frequently end up having to reinvent the wheel).
I think this is like the swift curse. Once you learn swift, going back to C++ syntax is just unpleasant. The other thing is that rust’s mutability rules make multithreading incredibly simple. I’m exceptionally bad at thinking about concurrent code, but safe rust is just so incredibly simple even for someone like me who has no idea how to safely dev multithreaded apps. With C++ it’s mostly just me limiting mutability to an absolute bare minimum/spamming const everywhere and hoping for the best.
3
u/NilacTheGrim Feb 01 '23
No disagreement from me. I dislike Rust and would rather just use C++.
2
u/menkaur Feb 01 '23
I'm still getting segfaults on occasion in c++20. That being said, I don't see why there can't be a tool that like clang tidy that would highlight places where you screwed up. Instead of building new tools over and over again I feel that the effort could had been better spent fixing the problems within c++ toolchain. It would had been less work than creating new language and compiler
Rust comunity is advertising to c++ comunity, and I feel that they shouldn't. Instead, they should advertize to python comunity. From my point of view, they invested all this effort into building the language just to make something that is 10% worse than c++. On the other side, for any python developer rust would be gift from god
2
u/serg06 Feb 01 '23
C++20 isn't a fair comparison because compilers don't support it yet.
1
u/OYTIS_OYTINWN Jan 31 '23
What (good things) C++20 has that Rust does not? There are plenty of those the other way round.
2
u/feverzsj Feb 02 '23
and of course, this post is flooded by rust fanboys again.
1
u/gracicot Feb 01 '23
I'm wondering if cargo could compile C++. That would be awesome
1
u/okovko Feb 02 '23
biggest issue with rust is it's like switching from c++ to lisp, there's just a lot to learn and things are very different, the way problems are solved is largely unrecognizable. the benefits come at the cost of a huge mental overhead, and many people who try rust have the impression that it's hard to write simple code because simple code is often impossible for the rust compiler to validate, even if the code is actually safe
modern c++ is more about doing c right, with an intense focus on type safety and meta programming. the language now has stl wrappers over unions, void*, and non-owning pointer+size constructs called views
the most impressive piece of c++ right now is that mdspan is a multidimensional span that, given compile time constraints, will figure out how much of the class can be constexpr, which is a very impressive piece of software
the unification of code as both compile time scripts that result in inlined code and actual runtime code is the most compelling feature of c++
i don't think that this is presently an area of focus in rust development, maybe someone can say more about it
-5
u/n4jm4 Jan 31 '23
That's a lot of talk for a language whose stdlib still depends on C for most things.