by danieljh · 11y ago · 0 comments
The add_one example, as simple as it is, is a horrible example.
Why not embrace value semantics and write it like:
int add_one(int x) { return x + 1; }
There is simply no need for pointers or references. Write simple code first. To the heap allocation example: auto x = std::make_unique<int>(5);
Even if this is a silly example, just say no to unnecessary heap allocation. Why not: int x{5};
Now to the lifted example: void add_one(std::unique_ptr<int> num) {
* num += 1;
}
This mixes operations with lifetime management. The add_one function does not need to care about ownership. And it does not need to take ownership of its argument. Instead on the call site do: int add_one(int); // from above
auto p = make_unique(5);
auto six = add_one(*p); // <-
There are valid points in the blog post and I know that most snippets are meant as examples. But as someone writing C++14 you can't win me with those kinds of posts, even though I'm having a fun time playing with Rust in my spare time.For more about modern practices see: http://klmr.me/slides/modern-cpp/
Also see Howard Hinnant's unique_ptr tutorial: http://howardhinnant.github.io/unique_ptr03.html
All of your examples look almost identical in Rust and C++. That's not a positive, nor is it a demonstration of similarity - it's a useless set of examples for a post _demonstrating the differences_ between the two. :P
It's worth looking at each of the examples in the article and thinking about them in the context of the more complex practical problem that do _require_ mutable/heap state.
Again, think of the examples as 'C-Reduce'd[1] ones - just enough for an experienced programmer to 'get' the differences and infer its relevance to real world cases.
To give at least one motivating example: for your first case (functional add one) - that's entirely passable for the (tiny) int, but quite useless for the larger case of BigInteger. That's where Rust's default move semantics would really shine, but using BigInteger as an example would introduce lots of irrelevant semantics, making the example bigger but scarcely more informative.
Where are the Rust explicit lifetimes in this example? If the C++ code has been made intentionally obtuse with unneeded measures here, why aren't Rust lifetimes (which I think are a terrible wart on the Rust language but are absolutely necessary for non-trivial ownership scenarios in Rust) captured in this example?
Rust has a feature called 'lifetime elision.' Three rules, that removed the need for virtually all (iirc, something lie 95%) of explicit annotations in the compiler.
The first rule is the one that applies here:
fn foo<'a>(x: &'a bar) {
can be written fn foo(x: &bar) {
That is, if there is only one lifetime annotation, it may be elided. The annotation wouldn't do anything special in this case, and so is just boilerplate.The point that I'm making is that learning about the necessity of explicit lifetime management in Rust, and the awkward syntax supporting it, was, for me, a splash of cold water in the face. I think that there are a lot of C and C++ programmers who read about Rust and read articles like this and get similarly excited about the prospect of static object lifetime management, but ask themselves whether it's really possible to completely hand lifetime management over to the compiler. And of course it isn't - sometimes you still need to concern yourself with the vulgar details of managing object destruction, and Rust's syntax for that is kind of ugly.
Blog articles like this are deceptive. Why are we exposing C++'s warts for the purposes of demonstration (and others here are right - the examples here are contrived) without mentioning something as ugly as explicit lifetimes in Rust? To make a point? What is that point?
See my point with making the add_one function not taking a unique_ptr. This is valid criticism and valid in more complex practical examples, too.
BigInteger& add_one(BigInteger& num)
is an awful function (really no checks of any kind, such as multiple holders). You suggest that it's valid for more complex practical examples, but that's a simple example where you'd probably want: void add_one(std::unique_ptr<BigInteger> num)
BigInteger is a common example often written in fluent/mutable style or to take ownership of the argument in just this way.The though-process goes like this:
* Do you need read-only access to the argument, take a const T&
* Do you need to modify the argument, take a T (by value), letting the call site decide to either pass an rvalue (move it, no copy), or an lvalue (copy)
There simply is no need for unique_ptr<BigInteger>, as BigInteger already handles its resources internally (with move semantics). It's the same reason as to why an owning pointer to a vector is silly when a vector already handles ownership of its resources.
http://klmr.me/slides/modern-cpp/#9 is exactly about this.
But in general, I think some of the advantages of Rust boil down to "compiler enforcement of stuff that good practitioners of modern C++ already do". And that's a good thing.
Thanks for your links, which are great!
Seeing last year's CPPCon videos was illuminating to me.
A big problem is that many are still writing pre-C++98 style or chained to style guides that prevent many of the C++11/C++14 improvements.
Specially problematic when IT is the one calling the shots to what is available in the development environments.
You can no-true-Scotsman code that compiles, runs, and blows up in your face with any modern C++ compiler all you want, it doesn't change the fact that Rust eliminates entire classes of errors that are trivial to hit in C++.
Until then, it is going to be "Modern" C++ for the lower layers/common code, with the platform vendor languages for the upper layers, regardless how Rust improves over C++.
I am a big fan of the type safety of Pascal and ML language families, but eco-systems have more weight than just the language.
If anything, this sort of post is more convincing to a junior developer who wants their compilers to do more to warn them when they've done something stupid. They want to write idiomatic C++, but they're lazy and inexperienced, so if there's a language where the compiler provides feedback when they deviate from what's idiomatic, they're going to opt for the feedback.
I'd be very interested in what's drawn you into trying Rust and what you think are the most redeemable qualities.
One thing I like about Rust is how you e.g. can specify a Sortable trait and then with T: Sortable require it for types. This will eventually come to C++ with Concepts (lite), for now there are ways to work around this, e.g. with:
#define requires(...) typename enable_if<(__VA_ARGS__), int>::type = 0
template <typename T, requires(is_integral<T>())>
void fn(T);
Without a feature like this you may see cryptic errors from inside template instantiations coming from your stdlib, when you try to sort something that is not sortable.Something I realized at some point is that these "language A vs language B" comparisons aren't really there to convince adherents of language B to switch to language A. You'll see lots of comparisons on the web of Haskell/Scheme/Lisp/C#/F#/Ocaml etc put up against really poorly written C/C++ code, with "language A" inevitably coming out of the comparison pretty well.
Thinking back to my days at school, a lot of physicists were telling each other that if they wanted their simulations to run in a reasonable amount of time, they had to code them in C. These comparisons are really aimed at them - the message here is, "yes, a really great C programmer could write machine-optimal FFTs or whatever in C, but the code that you, a beginner, will end up writing could actually end up being not much faster and in some cases perhaps even a lot slower than the equivalent code in Haskell/etc".
Compile time checking attracts more than just the lazy and inexperienced.
(Maybe you didn't mean to imply otherwise, but it sure as hell reads that way.)
I personally find C++ is fine and dandy if you're working with a disciplined team. On the other hand, it's bad qualities are immensely magnified when the overall team lacks in talent and/or experience.
There is a real difference between a safe language, and a safe subset of an unsafe language that gets verified by some guy (no disrespect). The former is (everything else being equal) just way better for everyone involved, especially for the guy.
hear, hear... Few of my recent features were passing through 7 layers owned by 4 teams (C++) with one team also having Java subteam (who seem to have never heard about Java coding style, etc...) Each team has a person who like you is enforcing his the _only_ right way ... which happen to be different from each other. Well, i just code to whatever style that module is written in :) After 25 years in the industry i've seen a lot of "right ways"...
>The add_one example, as simple as it is, is a horrible example.
>Why not embrace value semantics and write it like:
int add_one(int x) { return x + 1; }
>There is simply no need for pointers or references. Write simple code first.yea, man. That particular style is there too. Slow as hell. Works for the teams of really average programmers who can't grasp and keep together in mind more than one simple aspect of a small piece of functionality at a time.