|
|
|
|
|
by weinzierl
290 days ago
|
|
With Rust executing a function for either case deploys the “optimal” version (reference or move) by default, moreover, the compiler (not the linter) will point out the any improper “use after moves”. struct Data {
// Vec cannot implement "Copy" type
data: Vec<i32>,
}
// Equivalent to "passing by const-ref" in C++
fn BusinessLogic(d :&Data) {
d.DoThing();
}
// Equivalent to "move" in C++
fn FactoryFunction(d: Data) -> Owner {
owner = Owner{data: d};
// ...
return owner
}
Is this really true?I believe in Rust, when you move a non-Copy type, like in this case, it is up to the compiler if it passes a reference or makes a physical copy. In my (admittedly limited) understanding of Rust semantics calling FactoryFunction(d: Data)
could physically copy d despite it being non-Copy. Is this correct?EDIT: Thinking about it, the example is probably watertight because d is essentially a Vec (as Ygg2 pointed out). My point is that if you see FactoryFunction(d: Data)
and all you know is that d is non-Copy you should not assume it is not physically copied on function call. At least that is my believe. |
|
I believe the answer is technically yes. IIRC a "move" in Rust is defined as a bitwise copy of whatever is being moved, modulo optimizations. The only difference is what you can do with the source after - for non-Copy types, the source is no longer considered accessible/usable. With Copy types, the source is still accessible/usable.