113 points · by ephesee · 4y ago · 182 comments
`clang-tidy` is not letting you mutate or even access that moved-from "suffix" object without throwing an error.
It's annoying that you need `clang-tidy` and ASAN and shit to get comparable runtime safety even in greenfield C++, but that's not why to prefer Rust.
Prefer Rust because of a better traits system and pattern matching and syntax for `Maybe/Either` and a consistent build/library story and a number of other things.
But Rust vs. C++ is not an apples-to-apples comparison in this regard: Rust got a clean slate and was willing to cut ties with engineer-millenia of existing high-value software to do it.
In a perfect world Rust wouldn't be ambivalent at best and hostile at worst to C++ interop, c'est la vie.
Edit: how many languages have native C++ interop that supports the whole language? Would love to hear of any.
At least until Carbon is ready! But that's a few years away at the least.
Confused... so you're suggesting Rust's checks are somehow free of false positives? Doesn't the halting problem get in the way? One Rust-specific example: https://www.reddit.com/r/rust/comments/nr7a33/is_the_borrow_...
Memory safety in serious systems software is something that you approach asymptotically and/or probabilistically. Rust makes it easier to be memory safe in a lot of scenarios, at the cost of the father-knows-best borrow checker, but a crashed program is a crashed program whether I dereferenced a null pointer or was poking around in a slice with multi-byte Unicode characters in it. And that's before you get to `rg unsafe` on your favorite industrial-strength Rust codebase.
Rust is cool for so many great reasons that get talked about so little because everyone seems too busy acting superior about memory safety. Talk about traits! Or Cargo! Or the cool async stuff! Anything but another lecture on memory safety.
This sort of comment is far from fair and misses the whole point.
The thesis of this article is how programming languages compare with regards to safety.
It makes no sense at all to compare particular implementations and try to pass personal assertions on particular features of said implementations as broad assertions about the programming languages they support.
So a particular Rust implementation is bundled with a linter. That's pretty convenient.
It just so happens that the linter is provided by a compiler stack that is also one of the main reference implementations of C++, and said linter also supports C++.
Is it fair to thus claim Rust is somehow superior to C++ just because a particular implementation enables by default it's linter on Rust code but not C++?
> There's little reason for clang-tidy not to be part of the default clang invocation by now
It's perfectly fine that anyone forms their own personal opinion on what defaults a tool should ship with.
That says anything nothing about the programming languages and their safety though.
I try to keep in mind that on balance it’s a good thing that performant programs have become dramatically more accessible recently, and that most of the C/C++/Fortran/Haskell antagonism is a result of enthusiasm around that. For me it was BASIC -> C, but I imagine JS -> Rust is every bit as exhilarating.
But I do hope at least a few people read your comment and are inspired to learn a little background. Rust is cool because it remixed the broadly-accessible FP algebra, a kickass C++ toolchain decades in the making, and a big bet on linear typing.
I didn’t set out to be the jaded, un-hip old guy but here we are :) It’s a nifty new LLVM front end with type classes and the Either monad. Neat. Get off my lawn ;)
Devs that don't care only get to build on their own computers.
It isn't fullproof, but definitely helps to tame some cowboys.
* Rust has traits, but does not support OOP. Architectures where OOP is particularly effective are proving to be a significant challenge for Rust - GUIs are the obvious one, but also game development Rust projects have to invent new approaches.
* Option/Result make the code flow obvious, but having to return them in nearly all function calls is tedious. Rust has had several attempts at alleviating this problem, but still hasn't matched the convenience of exceptions.
* match is IMO syntactic sugar and its benefits for correctness are being oversold. The fact that one is basically obliged to use it leads to code that's sometimes too deep. Exceptions would cut through this error-handling noise, if they were available.
* The build story is convenient, but this had the unintended effect of encouraging dependency explosion. Adding typical crates results in dozens of transitive dependencies being included in a project.
The notable improvement that Rust brings to the table is machine-verified memory safety with C++-like performance, but that of course comes at the cost of having to adapt code to what the borrow checker understands. If one needs the feature, then the cost is worth paying, if not, Rust is more of a personal choice than an inevitable conclusion.
And finally, perhaps Rust's biggest sin is that it's big, it's complex and there's no end in sight to the complexity spiral, just like for C++. I can only imagine the chagrin of the Rust community as they see themselves competing with Go for many projects where performance is not absolutely critical and often being second choice exactly because of this complexity.
Among common uses for these more powerful features is to make misuse of the library into a compile-time error. Coding the library in Rust, if possible at all, would mean failing to prevent these usage errors.
The point here is that C++ puts more power in the hands of a library writer, and both the responsibility and capability to enforce safety in uses of the library. Rust jealously reserves maintaining safety to the compiler alone.
// hey don't pass in a temporary
auto make_appender(std::vector<int>&& suffix) = delete;
(which turns the provided code into a compiler error under both g++ and clang++) is adequate to prevent the immediate class of issues (namely, C++ allows const Foo& and Foo&& to bind to temporaries).Meanwhile, it's really really easy to make std::span dangle:
#include <cassert>
#include <span>
#include <utility>
#include <vector>
std::vector<int> append(std::vector<int>&& items, std::span<int> suffix) {
items.insert(items.end(), suffix.begin(), suffix.end());
return items;
}
auto make_appender(std::span<int> suffix) {
return [=](std::vector<int>&& items) {
return append(std::move(items), suffix);
};
}
auto make_appender34() {
std::vector<int> vec = {3, 4};
return make_appender(vec);
}
int main() {
auto append34 = make_appender34();
assert((std::vector<int>{1, 2, 3, 4} == append34({1, 2})));
}The point we should take away is that is actually hard to invent plausible examples of the failure that we are being told Rust would prevent.
I don't agree with that. If you can guarantee that the data pointed to by the span will outlive your appender, then it's safe. And if you don't actually want to transfer ownership or incur the overhead of a copy, and you don't care if your input is a vector or an array, then it's the correct abstraction.
Replace std::span with std::weak_ptr (or a raw pointer), and replace the closure with a class (e.g. a tree where each node has a weak pointer to its parent), and tell me again that nobody would ever write that code. It's fundamentally the same concept: if your ownership model isn't ironclad, or if any of your assumptions are ever violated, then you can run into use-after-free.
Closures only allow variables that are effectively final, aka you can’t reassign them (the compiler will stop you).
But you could pass an object and update its internal state.
What I mean is that what Java really "should" have is const like C++. A C++ function with a prototype of:
int doSomething(std::vector<int> const &x)
tells me much more than the equivalent Java: int doSomething(final List<Integer> x)
Also C++ member functions can declare themselves as not modifying their "this" instance. E.g. there's no way to write this code in Java: int X::doSomething(std::vector<int> const &x) const {
...
}
which is an extremely powerful, compile-time checkable description of what we are doing.It's not that final is useless (probably wrong choice of words there), what it does is okay and it's correct to use it as much as possible, but it's a far cry from the static guarantees afforded by const-correct code.
I also agree that the correct approach is immutability by default, but that ship has sailed, and it's also an orthogonal concern to what I'm saying here.
template<typename S>
auto make_appender(S&& suffix)
{
return [perf_fwd_suffix = std::tuple{std::forward<S>(suffix)}](std::vector<int>&& items)
{
return append(std::move(items), std::get<0>(perf_fwd_suffix));
};
}
see:
https://godbolt.org/z/M9P4MK4a8Another small thing: the C++ in this article looks weird to C++ programmers because it qualified vector with std, but does not qualify move.
I don't have anything against taking pride in one's skill and craftsmanship, but excusing a tool's failings purely on the basis that one needs more skill to wield it and avoid those failings? I want to have that same level of skill and have my tool multiply my skill's output to the max, not have my skill wasted coaxing my tool to perform correctly.
If the implication is that the tool requiring more skill gives commensurate benefits, fair enough, but not if it's just hand-waving away obvious downsides.
It would be one thing if this required skill, but this example is downright silly. Some other people here have posted more reasonable version, that might actually occur in the real world(like the example with std::span)
It’s a difference between “look this is Wally” (duh, of course) and a game of “Where’s Wally?”.
Whenever a CVE is discussed people say that the error is obvious, and no good programmer would write like that. It’s easy in hindsight.
The bad C++ code is in the very first line of the "make_appender" definition: capturing the closure's environment by reference is nonsense: It is equivalent to returning a reference to an argument. It is not, then, a closure at all.
Using a correctly-defined make_appender would not, then, produce undefined behavior when you use it, with or without "move".
What the author has done here was to take a too-obviously wrong operation, returning a reference to an argument, but dress it up with syntax that will look less familiar to some readers, and pass it off as insightful.
But using a wrong function and getting wrong results is not surprising.
Piling on more uses after, that give more wrong results, does not reveal anything more.
When you need disingenuous arguments to make your point, it tells us more about your point than about the thing you are trying to make a point about. And, publishing anyway tells us more about you.
Returning that fake closure should evoke a compiler warning, if you turn on warnings.
If it is so bad, it should (in the sense of how things would be in an ideal world) not compile.
>It is not, then, a closure at all.
It is a closure because all variables are closed-over and there are no free variables in the lambda body anymore. That is the definition of closure.
>But using a wrong function and getting wrong results is not surprising.
In an ideal world, there should be a compilation error. (There is in Rust)
The majority of what's wrong in C++ is that it lets you do nonsensical (even dangerous) things, most of the time without even a warning (and not because it's technically impossible to warn--it just didn't occur to them). It's okay to acknowledge that--it's a product of its time.
>Returning that fake closure should evoke a compiler warning, if you turn on warnings.
That "should" tells me all I need to know. In the end either safety is important, or it isn't. Choose accordingly.
Yes, C++ can be a bad solution to a lot of problems, and that's okay. Use rust if you need a machine guarantee for memory safety (or you just like the language), you can use Go if you just don't care about that at all and want the language to take care of it. But you can use C++ for non-critical software that needs to be fast (games come to mind). Rust can be too much of a mental overhead than it's worth for some.
That closure is just not a good example. Nobody would write this, because when writing C++ code you _do_ think about whether you want a reference or not. Sure, a lot of bugs can happen but this is not, in my opinion, one of them.
If you want to prove a point, prove it fairly.
Note: I don't use C++ anymore, and I don't like it very much for other reasons.
Rust has the least mental overhead of any language I've ever used. The compiler literally takes all the mental overhead away.
Not to disagree with your post but this comes across as very black-and-white.
There's a prioritized list of requirements in engineering. Use the right tool for the job.
Rust has: (see https://hackmd.io/@rust-ctcft/r1plN4You#/5 )
1. Safety
If you don't need that at the first slot, then the biggest strength of Rust doesn't apply to your problem (and you would waste time having to track lifetime parameters more than necessary to solve your problem).
std::vector<int> suffix{3, 4};
auto append34 = make_appender(suffix); // Version 1: test will work
auto append34 = make_appender({3, 4}); // Version 2: test will fail
I was in a mood to type the examples but I accidentally made Version 1 because I had started with the author's first example. I wondered where the problem was and couldn't find any (neither running nor reading the code) until I noticed the author had changed to Version 2.The problem is "obvious" in hindsight but one of the problems with C++ is that it makes certain things too implicit/convenient. I get that references are a staple feature in C++ but it's not at all obvious from the calling location that Version 2 is a bug. To see that, you have to navigate to the callee (finding which might be hard enough alone without a very solid IDE), and make sure that it's not capturing the argument by reference or not doing anything unsafe there.
It's often a problem when a seemingly "value" argument is turned into actually a pointer-to argument at the callee. There are other languages that have this too, and I've never liked it.
As someone who doesn't regularly code in C++ but has a solid understanding of the basics, I wonder why C++ ever allowed to have a reference parameter be called with a temporary? To me it feels like "References have value syntax but pointer semantics BUT you should program like it had value semantics"? Which to me would be exactly a premature optimization that is looking for trouble.
If you want copy in your C++ lambda, you start it `[=](...) {...}`, if you want take a pointer in your C++ lambda, you start it `[&](...) {...}`, if you want something trickier you do trickier stuff.
Rust opts you in to the nitpicky static analyzer and you have to opt out with `unsafe`, in C++ you have to opt in with e.g. `clang-tidy` or some annotations.
They are remarkably similar, just with different defaults.
I'm going to lead with this, because I think it's most important: Culturally there's a world of difference. Safety is a part of Rust's culture. "Culture eats strategy for breakfast".
Take sorting. In C++ the default sort is unstable, while in Rust the default sort is stable, that's just those defaults you mentioned (each has both kinds), although the choice speaks to culture. But look closer, in C++ the sort has undefined behaviour if your type isn't totally ordered. In Rust you can't sort the partially ordered types without saying how to order them fully. Still, in both languages we can write a custom order, so what happens then? In C++ if your custom order is nonsense you get... undefined behaviour. In Rust sorting won't necessarily work with a nonsense custom order but the behaviour remains well defined.
> Rust opts you in to the nitpicky static analyzer and you have to opt out with `unsafe`
Unsafe gives you a small number of dangerous "super powers" needed to write efficient low-level code, it does not opt out of the borrow checker's analysis, or indeed most other checks. This misconception makes me wonder how much of what you've written is conjecture rather than practical experience.
It doesn't help that those of us that care about enabling the right defaults are a tiny minority as per C++ surveys.
https://blog.jetbrains.com/clion/2021/07/cpp-ecosystem-in-20...
I think the point the author tries to make is that, while C++ and Rust are probably "the same" for the most skillful and disciplined programmers (such as you), for average human, Rust just catches way more errors they make for them early. An extreme analogy would be trying to climb Everest all by yourself vs with a professional guide.
I suspect that the adoption of Rust as a system language is going slower because that's just the natural pace of embedded/systems development, not because of anything intrinsic to Rust. There are now 30k+ lines of Rust code [1] in the Linux kernel. C++ can't claim that.
That's just as true of Rust if you use clone(), Rc<> and RefCell<>. You just have to familiarize with a few boilerplate patterns, and the best part is you're only trading off a modicum of performance while preserving safety. But Rust can work quite well as a language for exploratory programming.
Industry clearly prioritises speed of delivery above all else. Security, reliability and maintenance are future problems (that would be nice to have).
However, in order to gain the power to reason about our code and be able to prove the correctness of various properties (what a typechecker does), we have to program with more restrictive models. This has been argued many times before (e.g. Dijkstra's structured programming). Haskell and Rust are just two of many examples. My favourite is regular expressions, choose actual proper regexes and you have guaranteed O(n) execution, choose Perl/Python "Regex" and you have a potential security hole.
There was (and still isn’t) a competitor that can compete on the same level with Javascript in the browser.
<source>:21:35: warning: temporary whose address is used as value of local variable 'append34' will be destroyed at the end of the full-expression [-Wdangling]
auto append34 = make_appender({3, 4}); test.cpp:16:45: error: Using object that is a temporary. [danglingTemporaryLifetime]
assert((std::vector<int>{1, 2, 3, 4} == append34({1, 2}))); // FAIL: UB
^
test.cpp:3:12: note: Return lambda.
return [&](std::vector<int>&& items) {
^
test.cpp:2:50: note: Passed to reference.
auto make_appender(std::vector<int> const& suffix) {
^
test.cpp:4:36: note: Lambda captures variable by reference here.
return append(move(items), suffix);
^
test.cpp:15:35: note: Passed to 'make_appender'.
auto append34 = make_appender({3, 4});
^
test.cpp:15:35: note: Temporary created here.
auto append34 = make_appender({3, 4});
^
test.cpp:16:45: note: Using object that is a temporary.
assert((std::vector<int>{1, 2, 3, 4} == append34({1, 2}))); // FAIL: UB error: Syntax Error: AST broken, binary operator '!=' doesn't have two operands. [internalAstError]
explicit operator bool() const { return this->get() != pointer(); }
This is for a simple wrapper class that looks like this: template<class T>
class Foo : private Bar<T> {
public:
typedef value_type *pointer;
pointer get() const { return ...; }
explicit operator bool() const { return this->get() != pointer(); }
};
Another example: void foo(uintptr_t const (&input)[2]) {
if constexpr (sizeof(uintptr_t) == sizeof(int) && sizeof(long long) == 2 * sizeof(int)) {
long long value;
memcpy(&reinterpret_cast<uintptr_t *>(&value)[0], &input[0], sizeof(input[0]));
memcpy(&reinterpret_cast<uintptr_t *>(&value)[1], &input[1], sizeof(input[1]));
}
}
error: The address of local variable 'value' is accessed at non-zero index. [objectIndex]
memcpy(&reinterpret_cast<uintptr_t *>(&value)[1], &input[1], sizeof(input[1]));
^There isn't a right and wrong here: sometimes you want to opt in to the check for that, sometimes you want to opt out of it.
Sometimes I actually do want to fuck with addresses on the stack in weird, potentially architecture-dependent ways, it's rare but it happens.
I happen to think that Rust's linear/affine typing is by far the most usable low/zero-cost memory management model that anyone has demonstrated at scale and a real achievement in practical computer science, but it comes at a pretty serious cost in `Box`-this and `Arc`-that and `Rc`-other-thing and generally the borrow-checker being a PITA about some stuff we're used to doing.
Rust is very cool and I use it, but the "using C/C++ is fucking strangers without protection"-vibe got old years ago.
What matters is the lifetime, where the object lives is a rule of thumb for guessing lifetime that results from C++ trauma.
Getters that return references are code stink.
source: consultant, seen some truly heinous Go monoliths.
It's only my gut feeling, but does that match your experience ?
append34 := func() func([]int) []int {
If I was going to rank the readability I would say:1. Rust function bodies 2. Go code 3. Rust function signatures 4. C++ code
Which you could argue is me shifting the boundaries a bit, but sufficiently statically typed languages seem to develop two (or more) sublanguages. Global complexity definitely pushes Rust down peg.
https://go.dev/blog/declaration-syntax
Go's type syntax is unusual but supposedly much clearer when things get more involved.
Probably not, and to be fair anyone else's preference is equally valid. I think largely what individuals consider most readable depends less on what's being read and assessed now, and more on what route a developer has taken to reach this point in their career.
If I'm honest it's more about unconscious familiarity with idioms and constructs than it is an isolated unbiased opinion.
And I'd probably also change my comment slightly to say that by "Go code" I really did mean the actual code doing the work; I find the tests far less appealing.
Probableur a typeaux?