FAQ - Help and questions

How do C++ move semantics differ from moves in Rust?

#porting#cpp#ownershippublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

In Rust every assignment or call by value of a non-Copy type is a move, and the compiler forbids using the old name afterwards, so there is no moved-from object to keep valid. C++ needs std::move and a valid empty state. Where you need a replacement left behind, use mem::take or mem::replace.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

In C++ a move is an optimisation you ask for with std::move. The source object is still there afterwards, in a "valid but unspecified" state, and the language lets you use it. Every class that supports moving needs a move constructor, a move assignment and a moved-from state to design and test.

In Rust a move is the default for every type that is not Copy, and the compiler treats the source as gone. There is nothing to design: no move constructor to write, no empty state to maintain, and no destructor call for the moved-from variable. Using the old name afterwards is a compile error:

src/main.rsrust
fn consume(v: Vec<i32>) -> usize {
    v.len()
}

fn main() {
    let v = vec![1, 2, 3];
    let n = consume(v);
    println!("{n} {}", v.len());
}
text
error[E0382]: borrow of moved value: `v`
 --> src/main.rs:8:24
  |
6 |     let v = vec![1, 2, 3];
  |         - move occurs because `v` has type `Vec<i32>`, which does not implement the `Copy` trait
7 |     let n = consume(v);
  |                     - value moved here
8 |     println!("{n} {}", v.len());
  |                        ^ value borrowed here after move
  |
help: consider cloning the value if the performance cost is acceptable
  |
7 |     let n = consume(v.clone());
  |                      ++++++++

The message was shortened (and the file name shown as src/main.rs; it was compiled from a scratch file). It shows the three ways forward: pass a reference (&v) if the function only reads, move and stop using the name, or clone() to make an explicit copy.

When you do want a valid replacement left behind (what C++ gives you automatically, with a moved-from empty std::string), say so with std::mem::take or std::mem::replace:

src/main.rsrust
fn consume(v: Vec<i32>) -> usize {
    v.len()
}

fn main() {
    let mut name = String::from("config");
    let taken = std::mem::take(&mut name); // moves the text out and leaves a valid empty String behind
    println!("taken={taken:?} left={name:?}");
    let old = std::mem::replace(&mut name, String::from("fresh"));
    println!("old={old:?} now={name:?}");

    let v = vec![1, 2, 3];
    let n = consume(v.clone()); // an explicit copy, visible in the code
    println!("{n} {}", v.len());
}
text
taken="config" left=""
old="" now="fresh"
3 3

How to do it#

  1. Where C++ copied an object because the copy constructor was implicit, Rust makes you write .clone(). Look at each one: do you need the copy, or can the function take a reference?
  2. Where C++ used std::move(x), write x (the move is automatic). Remove later uses of x, or restructure.
  3. Where C++ code relies on a moved-from object being reused (a buffer that is emptied and refilled in a loop), use mem::take, or clear the collection with .clear() and reuse it.
  4. Where a type is small and plain (numbers, a pair of coordinates), derive Copy and Clone, and the move question disappears: copies are cheap and implicit.

Common mistakes#

  • Adding .clone() at every error. Each is a real copy. Count them in hot code (see the thread on why a port can be slower).
  • Expecting a destructor to run for a moved-from value. In Rust the value is dropped once, by its final owner.
  • Moving out of a vector element by index (let x = v[0]; for a String). The compiler rejects it because the vector still owns the element; use v.remove(0), std::mem::take(&mut v[0]), or borrow.

Is a Rust move expensive?#

A move copies the value's bytes (a Vec is a pointer, a length and a capacity) and does not touch the heap data. The compiler may then remove even that copy. This thread did not measure it.

How does this relate to copy elision and RVO?#

Returning a value from a function is a move in Rust, with no special rule to learn.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet