0

Simple example of code only for illustrative purpose:

struct A {
   fieldOne: String;
}

fn main() {
   let x = A { fieldOne = String::from_str("testtest") };
   let y = x; // a move performed
}

Is the x object destroyed (dropped) immediately after the move or it will be dropped only after going out of scope?

  • @Chayim Friedman I've read the whole post by the given link, but n't found a precise description of after-move behavior, only a statement, that Rust forbids to use a previous owner of resource after move in compile-time. But what about run time? For example, I can have a bunch of quite heavy objects, move all of them, and what goes after that? If almost all moves in Rust are just memcpy() and the previous owners only destroyed when they leave the scope, we can have a situtation of 2x memory consumption until an execution flow reaches end of a block, where a half of consumed memory is garbage. – Nikita Glukhov May 04 '22 at 00:15
  • *"Is the `x` object dropped immediately after the move or it will be dropped only after going out of scope?"* - The variable `x` will not be dropped at all, after the move it no longer has a value. The *value* originally assigned to `x` was moved to `y` and such will be dropped when `y` goes out of scope. At no point is there ever 2 `A`s, you only made one. – kmdreko May 04 '22 at 01:30
  • 1
    I think you also are confused about what *"moves in Rust are just `memcpy`"* means because it only applies to the stack-allocated part of an object, which for `String` and thus for `A` is just a pointer, size, and capacity. The `"testtest"` is not copied as part of a move. – kmdreko May 04 '22 at 01:32
  • The optimizer will also elide this move. The effect on the generated code by `let y = x;` is going to be nil. – cdhowie May 04 '22 at 02:10
  • @NikitaGlukhov The second answer on the linked duplicate answers the question you posed. – cdhowie May 04 '22 at 02:14
  • @kmdreko I've searched similar questions about Rust's movings on SO, it seems that "destructive move" implementation via ```memcpy``` and compile-time forbidding of the previous variable binding, performs, roughly speaking, "logical" ownership tranferring but not an actual move (it could be optimized by the rustc backend afterwards, though). So, if I have a big array, allocated on the stack, and "move" it, memory will not be deallocated from the stack 'til end of a code block, just unreachable. There are recommedations to ```Box``` big objects to make impact of Rust's way of moving negligible – Nikita Glukhov May 04 '22 at 10:25

0 Answers0