6

An article that I read recently stated that a struct that holds a Box<T> as a field is not Copy.

This confuses me, since I thought that any type whose size is known can be stored on the stack - and is therefore Copy.

Isn't the Box's size always the same? I thought that it was just a reference to a heap allocated memory - and does therefore have always the same size.

Bless
  • 5,052
  • 2
  • 40
  • 44
Dominik
  • 89
  • 1
  • 6
  • 2
    *any type whose size is known can be stored on the stack - and is therefore `Copy`* — that's not what [`Copy`](https://doc.rust-lang.org/std/marker/trait.Copy.html) means. Did you read the documentation? Why do you have this belief? Please link to the article. – Shepmaster May 13 '19 at 19:21
  • I believe your question is answered by the answers of [How do I implement Copy and Clone for a type that contains a String?](https://stackoverflow.com/q/38215753/155423) (`String` is basically a `Vec` and a `Vec` effectively contains a `Box`). If you disagree, please **[edit]** your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster May 13 '19 at 19:23
  • 2
    See also [How can I implement Rust's Copy trait?](https://stackoverflow.com/q/35458562/155423); [What is the difference between Copy and Clone?](https://stackoverflow.com/q/31012923/155423); [Do copy semantics in Rust literally become a copy in memory?](https://stackoverflow.com/q/32663478/155423); [Why is the Copy trait needed for default (struct valued) array initialization?](https://stackoverflow.com/q/27876588/155423). – Shepmaster May 13 '19 at 19:25
  • I think that the answer in "How do I implement Copy and Clone..." also fits for my question: "because String contains a pointer to the string data on the heap and assumes it has unique ownership of that data" - I guess this is true for Box, too. So the Box's size itself would be known at compile time, but the problem is the actual pointer, isn't it? – Dominik May 13 '19 at 19:32
  • 3
    Yes, the size of a `Box` is always known at compile time — it will be one machine-sized integer (for normal types) or two (for fat pointers). The reason that `String` / `Box` / `Vec` cannot be `Copy` is that, if they were, then two values would "own" the same underlying memory allocation. When the first went out of scope, the value would be deallocated. The remaining value would then point to invalid memory. – Shepmaster May 13 '19 at 20:41

0 Answers0