9 ms·
Short intro to C++ for Rust developers: Ownership and Borrowing
- heinrich5991 10y agoThis glosses over "rvalue references", which is roughly what Rust does when you pass a parameter without any further qualification (references, boxes).
- ycmbntrthrwaway 10y agoCan you give an example? Is void foo(T&& value) { ... } similar to fn foo(value: T) { ... } ?
- krona 10y agoBoth are similar in the sense that `foo` owns `value`, yes. Or at least that's the idea. In C++, it's up to the author of T to implement such semantics (through its move constructor) correctly for non-trivial types.
- be21 10y agoIn most cases maintainability wins, and avoiding “premature optimization” is very much a necessity in C++. I agree with this conclusion. Quite often, when you start coding you don't know, where the performance bottlenecks hide, and you don't want to waste time, thinking about allocating memory for a routine which you could write equally well in any scripting language. Unfortunately plugable automatic garbage collection for less verbose performance uncritical scripting tasks within the language is not usable.
- sbuttgereit 10y agoI don't come from a even vaguely C or C++ background, but have been studying Rust for some time; most development work that I do is executed in very high level languages. I know generally the concepts that exist in C & C++ and absolutely no idea how and why you'd use them as opposed to other tools (OK... an overstatement, but you get the idea). Much of this is because I've not tried to write any C/C++ and only even read it when I need to generally know what some feature of an application does. This article actually helped me understand C/C++ a little bit better than I did before. For example where it explained the differences between Rust and C/C++ copy vs move behavior... I got a better sense of just how C/C++ works and why I might chose to write, say, a function parameter one way vs. another. So in this basic sense, mission accomplished I think. I have no doubt there's lots of nuance missing, but still... not bad and I appreciate the effort.
- banachtarski 10y agoOh boy there are some serious errors here. Returning a stack allocated value does not invoke the move constructor. It doesn't copy either. This is a separate optimization that existed even prior to C++11 called the "named return value optimization" or NRVO for short. And by "sufficient new compiler" you really should just say every compiler. No compiler I know of in existence used by actual people doesn't implement this. Here's a demo: http://ideone.com/QRqj5P http://ideone.com/QRqj5P It's VERY important that this optimization isn't confused with move construction as the latter would actually be extremely less performant than what actually happens.
- Manishearth 10y agoI think this is due to a confusion between the two kinds of "move" in the article. Returning a value from a C++ function is a "move" in the Rust sense. It's not a move in the C++ sense, since C++ moves involve move constructors. It's probably this confusion that led to it being written that way, probably should be fixed.
- banachtarski 10y agoHe has a line where he writes return val; // val is `rvalue` here This is the part that isn't accurate. "val" is a named reference and is not an rvalue. There isn't any "moving" up the stack that happens. He's likely confusing this with an expiring value (a subtype of rvalue) that happens in code like foo(returns_something()); The returned value from returns_something() is un-named and is about to die after this line executes (lives until foo's invocation unwinds) and so it is an rvalue. You can't have a named rvalue unless you std::move explicitly I don't think.
- StephanTLavavej 10y agoIt's a little more subtle than that. "val" is definitely an lvalue. However, when returning a local variable like this, C++11 has a rule: "if the NRVO activates, there are no copies/moves. Otherwise, see if you can treat val as an rvalue - if so, you get a move. That almost always works, but if it doesn't, fall back to treating it as an lvalue so it compiles with a copy like it used to." This is the one time in the language that lvalues are automatically moved from, and it's because the language/compiler knows that returning from a function will destroy all local variables, so it's safe to move from them.
- WhitneyLand 10y agoWhy should "get_first_name_mut" not be simplified to "first_name"?
- sidlls 10y agoWhy should it be?
- db48x 10y agoget_foo and get_foo_mut are a convention used by the rust standard library.
- ycmbntrthrwaway 10y agoMostly because Rust does not support overloading and you may want both mut and non-mut versions.
- jeremyjh 10y agoIf you don't want unnecessary copies, the first tool you should reach for in C++ would be a const ref. I can't think of a reason I'd want to copy a string implicitly - better to pass a const ref and explicitly copy it so that the next guy (me a week later) doesn't waste time figuring out if that was a mistake.
- StephanTLavavej 10y agoThat guidance isn't correct in the C++11 New World Order. For maximum performance, you must think about move semantics. Simply saying const X& everywhere will inhibit move semantics (can't move from const, can't move from lvalues, especially can't move from lvalue-ref-to-const). For example, suppose you're writing a FancyAppend() function, that will return "LhsString, RhsString". Following your guidance, the signature would be "string FancyAppend(const string&, const string&)". While that definitely avoids copying the inputs, it is not optimal. Providing additional overloads for string&& parameters can be more efficient (if at least one input is a modifiable rvalue, it can be appended to in-place, which can avoid additional memory allocation if it happens to have sufficient capacity; for repeated appends, this can avoid quadratic copying of elements). Indeed, this is what string's operator+() does. Note that working with rvalue references does require more understanding. For example, the signature "string&& BadAppend(string&&, const string&)" is a severe error (one that the Standardization Committee made early on, and corrected before shipping).
- AstralStorm 10y agoAnd if you support both const arguments, maybe whole or part of the function can be declared constexpr. (or pure in C++17 or is it even 14)
- StephanTLavavej 10y agoThere's no such thing as "pure" in Standard C++ yet, even the C++17 Working Paper.
- 10y ago
- andy_ppp 10y agoThis is probably the best explanation of Borrowing and Ownership I have seen.
- simplehuman 10y agoYou haven't read much then
- ThePhysicist 10y agoThe important thing to remember about `std::move` in C++ is that it doesn't move anything, it simply does an unconditional cast to an rvalue reference, which basically allows you to treat the object as a temporary variable (effectively transferring ownership).
- timClicks 10y agoA very good resource for C++ developers is Nick Cameron's r4cppp tutorials https://github.com/nrc/r4cppp https://github.com/nrc/r4cppp
- solidsnack9000 10y agoThis really puts the ownership features of Rust in perspective: they are certainly no more involved than what's going on in C++. Harder than Python, yes; excessive compared to Haskell, sure; but here we see what Rust is really comparing itself too. (This is not to say, that it's always what we should be comparing it to.)
- general_ai 10y agoTherein lies the perception problem: a lot of folks think that C++ is a static target, but it's not. It has improved by leaps and bounds over the past decade or so, and will improve a lot more this year when C++17 support becomes widespread. I find anything from C++0x onwards pretty pleasant to work in if you're on a UNIX-like OS. Windows is another story entirely.
- alfalfasprout 10y agoComing from a Linux/OSX world I had to port a library to Windows the other day. That used to be an utter nightmare with C or pre-C++11 codebases. I actually found it pretty painless. The only things I found annoying were the various syscalls and interacting with the crypto libraries (and you thought openssl was ugly...). Modern C++ is pretty darn nice to work with. It's not a "safe" language by any means, but with good tooling, design, and a good static analyzer you can prevent the vast majority of memory bugs you'd run into with C. Plus the compilers are so mature you get great performance right out of the box.
- general_ai 10y ago>> you get great performance right out of the box Yup. And if you don't you can drop all the way down to intrinsics and assembly. It's pretty nice.
- pjmlp 10y ago> Windows is another story entirely. Actually Windows has always enjoyed better C++ related tooling than any UNIX other than Mac OS X. And standards compliance is actually the best one among commercial C++ vendors.
- AstralStorm 10y agoExcept the most important one, that is Microsoft. Only newest versions are passable. EDG does not support C++14. Embarcadero (C++ builder) is also behind. ICC I'm not sure, but should be modern. Other important commercial windows compilers I missed?
- criddell 10y agoI have a C++ question. In the article, the author writes the Person constructor this way: Person(std::string first_name, std::string last_name) : first_name(std::move(first_name)) , last_name(std::move(last_name)) {} For string parameters, do you need to use std::move()? Won't the compiler do that anyway? And does anybody really put the comma separating initializers at the start of the line? Yuck.
- kchoudhu 10y agoI do. Easier to comment things out when necessary. Hangover from SQL as well.
- flukus 10y agoI wish trailing commas were more widely supported in programming languages.
- GrayShade 10y agoIt's the same. You can comment out the last line easier, but not the first one. With trailing commas, it's the other way around.
- masklinn 10y ago> With trailing commas, it's the other way around. If the language supports trailing commas[0] (rather than just interspersed ones) that's not an issue as you could write: Person(std::string first_name, std::string last_name): first_name(std::move(first_name)), last_name(std::move(last_name)), {} [0] as Python, Ruby, Javascript or Rust do
- tomjakubowski 10y ago> And does anybody really put the comma separating initializers at the start of the line? Yuck. I don't, but I can see why someone would. When you copy-paste initializer lines around (say, because you've re-ordered members in the declaration), a leftover trailing comma often leads to insanely painful compiler errors. Organizing the commas this way makes that less likely.
- partycoder 10y agoIn theory you can achieve a lot in C++. But C++ is like a large buffet where you can pick from a lot of different abstractions. Rust on the other hand is not as flexible. But it rather tries to focus in safer abstractions, and provide convenience and coherence around them.
- akiselev 10y ago> Rust on the other hand is not as flexible. How so? If you want the same flexibility as C++ memory safety wise, you just use the unsafe keyword when you need to. A lot of Rust programmers are scared of unsafe blocks for some reason but writing unsafe code in Rust is no less safe than writing regular C/C++ except you can choose to reenable safety whenever you want to. You have to look out for subtle bugs that come up when safe code makes assumptions about unsafe code that you don't properly implement but these are logic bugs, same as you'd find in any other language when a module breaks a contract. Just don't use unsafe willy nilly in a library crate that you expect other people to use. As far as the rest of the language, I find Rust's traits to be far more flexible than C++ OOP, it just takes a little while to adapt to thinking in trait based composition. Once trait specialization and "impl Trait" hit stable and the Rust team figures out how to make the ambiguity rules less conservative, we'll have the best of both worlds: interfaces (both dynamic and static), trait based composition, and inheritance (you can already do regular OOP inheritance with a little bit of boilerplate like how Servo uses Upcast<T>/Downcast<T> traits for HTML object hierarchies). Both are currently in nightly (impl Trait might be beta already).
- partycoder 10y ago"unsafe" is expressing that you are opting-in for less safe code. Same in C#. Many unsafe abstractions are not opt-in in C++. You can go ahead and writing them. No warning or cost. "mut" and "unsafe" are keywords that you need to write down each time. They're keywords you can spot easily during a code review and say "how do you justify this?". Rust's language design choice of having everything being immutable and safe by default is a great idea.
- 10y ago
- AstralStorm 10y agoThe proper way to avoid problems with use after move would be an instrumented compiler adding a check. You can partially do it on your own, but it might be more expensive. (That by employing pointers or sentinels.)
- rosshemsley 10y agoOne useful rule of thumb that works 99% of the time in C++11 is: Never use "std::move" It's really just there to allow fancy optimisations and you don't need it in most cases. You should rely on the sane defaults instead: - Putting variables on the stack to manage object ownership/lifetime is a good default. - Use std::unique_ptr or std::shared_ptr() for heap ownership (single ownership vs. shared) - For a non-owning (mutable) reference, use const & (&) or const * (*) when the value may not exist. - Always prefer passing by value (return types and parameters) - If a parameter type is heavy, take a (const) reference. - If the return type is heavy, the compiler's RVO will do its job. No need to be more fancy than this
- konstmonst 10y agoI disagree with you opinion on that. If you don't understand something doesn't mean that this is just for fancy optimizations. Essentially you use std::move when you want to have pointer semantics without using a pointer. You don't want to use a pointers sometimes to keep objects on stack and use it to track ownership. So instead of doing C* c1 = new C; C* c2 = c1; You have C c1; C c2 = c1; // here I have a move constructor which moves c1 to c2, c2 is now a null object. This is what rust is able to do and you don't need expensive atomics (shared_ptr), ugly template syntax (unique_ptr), can keep everything on the stack and (!) have the objects be automatically cleaned up correctly.
- rosshemsley 10y ago> If you don't understand something doesn't mean that this is just for fancy optimizations. You should definitely understand it, but if you find yourself wanting to use it, you should start by considering alternatives first. It's a sharp (and often unsafe) tool that should be avoided in most cases. For your example, unique_ptr is the correct (and safe) solution and will do the same thing. > you don't need expensive atomics (shared_ptr) Note that shared_ptr provides no "atomicity". It is in reality exceptionally cheap.