Reputation: 2201
The Rust doc defines Copy
marked types as
Types whose values can be duplicated simply by copying bits
I wonder whether this definition means copying a variable value from only the stack or it includes copying heap resources too? In other words, is Copy
just a sign for the compilier with a notice like "If you're going to create another variable of this type with the same value as one has, just copy all concerned with the first variable from the stack. That's sufficient to do."?
What if I have a type whose objects allocate a resource in a heap and I'm sure no dreadful thing would be coming up in the case of bit copying of this resource by means of memcpy
or something. Can't I still denote the type with Copy
(in due to Rust does only stack copying)?
Upvotes: 2
Views: 610
Reputation: 154916
I wonder whether this definition means copying a variable value from only the stack or it includes copying heap resources too?
It's the former. It refers to copying a value by performing a naive and shallow byte-by-byte copy of its data.
More precisely, Copy
means "it is safe to bitwise-copy the value and keep using the original value". All Rust objects are bitwise-copied in principle, be it by assignment or passing to functions, etc. The difference when the object is not Copy
is that the object is said to be moved, and the compiler doesn't allow you to access the object that was the source of the copy. (The compiler will also not drop the original object if it implements Drop
because it will be dropped by the new owner.)
In other words, is Copy just a sign for the compilier with a notice like "If you're going to create another variable of this type with the same value as one has, just copy all concerned with the first variable from the stack. That's sufficient to do."?
Yes.
What if I have a type whose objects allocate a resource in a heap and I'm sure no dreadful thing would be coming up in the case of bit copying of this resource by means of memcpy or something. Can't I still denote the type with Copy (in due to Rust does only stack copying)?
There is no way (and will likely never be a way) to denote such a type as Copy
. If you want to allow copying such objects, you have to make them Clone
and require the user to type .clone()
explicitly. That's one of the things meant by claims that Rust "makes allocations explicit".
Note that none of this requires either the source or the destination of the copy to be allocated on the stack. They could as well be sub-fields of heap-allocated objects, and the same principles would apply equally. The "stack" is irrelevant: what matters is whether the byte-by-byte value transfer is considered a "copy" or "move", and that will depend on whether the type is Copy
.
Upvotes: 7