kaist-cp/cs431

[Question] mem::swap with temporary value

Closed this issue · 3 comments

In function mem::swap(&mut x, &mut y), what happens if y is a temporary value?

For example, mem::swap(&mut s, &mut String::("temp string")).

If I run it, the value of s is swapped correctly to "temp string", but I am worried if there will be some weird behaviors in the behind.

Also, I wish to know how temporary values are treated in memory.

My guess is that the temporary values are allocated explicitly in memory (both for stack and heap) and dropped immediately after returning to caller. Am I right?

Yes you are correct.

mem::swap(&mut s, &mut String::("temp string"))
                       ^^^^^^^^^^^^^^^^^^^^^^  - and dropped here
                       |
                       temporary variable is allocated here (with usual allocator function)

See a related compiler message that might give you insight on how lifetime of temporary variables are treated in Rust.
https://users.rust-lang.org/t/rust-and-strings-what-is-the-deal-with-temporary-value-dropped-while-borrowed/98424

Another resource: https://doc.rust-lang.org/reference/expressions.html#temporaries

Thank you!

BTW, in this case you probably want mem::replace