Reputation: 85462
The Rust Copy
trait makes this remark:
Under the hood, both a copy and a move can result in bits being copied in memory, although this is sometimes optimized away.
The documentation provides this code for reference:
// We can derive a `Copy` implementation. `Clone` is also required, as it's
// a supertrait of `Copy`.
#[derive(Debug, Copy, Clone)]
struct Foo;
let x = Foo;
let y = x;
// `y` is a copy of `x`
println!("{x:?}"); // A-OK!
y
) was actually copied in memory or optimized away (by reusing the location of x
)?Upvotes: 2
Views: 354
Reputation: 26609
How does one modify this code so that we can detect (and print) at runtime as to whether a variable (y) was actually copied in memory or optimized away (by reusing the location of x)?
You can't. Whether a copy of the memory is optimized away or not is purely up to the compiler, as long as it can prove that the resulting code is equivalent. And because the resulting code is equivalent, 99% of the time you don't need to care.
C++ lets you detect when memory has changed places via copy and move constructors. However, to simplify things, Rust explicitly requires that structures be movable via a simple memory copy, and does not provide a mechanism to specify a custom move implementation.
Are there any resources to understand the innards of what's happening here?
Beyond looking at how LLVM optimizes code, no.
Upvotes: 3