Is there a way to have a Rust closure that moves only some variables into it?

Yes, it is possible to move only one or some variables into a closure (rather than all or none). Yes, this can be used to “circumvent” reference counting. I found an answer in the documentation of rayon::scope that turns out to be exactly about this problem: ‘Accessing the stack data [from within a scoped threads … Read more

How does std::move convert expressions to rvalues?

We start with the move function (which I cleaned up a little bit): template <typename T> typename remove_reference<T>::type&& move(T&& arg) { return static_cast<typename remove_reference<T>::type&&>(arg); } Let’s start with the easier part – that is, when the function is called with rvalue: Object a = std::move(Object()); // Object() is temporary, which is prvalue and our move … Read more

Why can you return a std::unique_ptr without std::move?

is there some other clause in the language specification that this exploits? Yes, see 12.8 §34 and §35: When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object […] This elision of copy/move operations, called copy elision, is permitted […] in a return statement in a function … Read more

What is the “rvalue reference for *this” proposal?

First, “ref-qualifiers for *this” is a just a “marketing statement”. The type of *this never changes, see the bottom of this post. It’s way easier to understand it with this wording though. Next, the following code chooses the function to be called based on the ref-qualifier of the “implicit object parameter” of the function†: // … Read more

Why is there no default move-assignment/move-constructor in early drafts of the C++11 standard?

The implicit generation of move constructors and assignment operators has been contentious and there have been major revisions in recent drafts of the C++ Standard, so currently available compilers will likely behave differently with respect to implicit generation. For more about the history of the issue, see the 2010 WG21 papers list and search for … Read more

Is it necessary to std::move in a return statement, and should you return rvalue references?

First example std::vector<int> return_vector(void) { std::vector<int> tmp {1,2,3,4,5}; return tmp; } std::vector<int> &&rval_ref = return_vector(); The first example returns a temporary which is caught by rval_ref. That temporary will have its life extended beyond the rval_ref definition and you can use it as if you had caught it by value. This is very similar to … Read more

C++11 move when returning a lock

It’s fine with or without the std::move. The name of a local variable* is treated as an rvalue in the return statement, causing the move constructor to be invoked in both cases. The authors presumably used std::move for stylistic reasons, to make it clear that the lock is being moved. It does interfere with NRVO, … Read more