Finlay Weber
Finlay Weber

Reputation: 4153

Is Clone for copying on the heap, while Copy for copying on the stack in Rust?

As the title says, will I be correct to say that Clone for copying on the heap, while Copy for copying on the stack in Rust?

This is basically what this article here says, but I have doubts over its correctness.

Upvotes: 4

Views: 2088

Answers (2)

kmdreko
kmdreko

Reputation: 59882

Copying vs cloning do not equate to stack vs heap. Copy and Clone are traits which are properties of the type, not properties on where the value lies. They are more closely tied with ownership than memory region.

Consider this example where integers are stored on the heap (via Vec) and I copy from one element to another. This uses Copy (because there is no explicit .clone()) and yet both the source and destination are on the heap:

let mut v = vec![0i32; 10];
v[0] = v[1];

Consider this example where a RefCell is stored on the stack, and uses Clone to get another of the same. Both elements are on the stack and yet I must use .clone() because RefCell does not implement Copy. A RefCell doesn't use any heap allocations either:

let rc1 = RefCell::new(...);
let rc2 = rc1.clone();

A type implementing Copy simply means that it can be bitwise-copied from one memory location to another and have both instances be equally valid.

What is important for comparing Copy and Clone is if there is additional meaning that needs to be applied when the type is created or destroyed beyond the in-place data it holds. Having ownership over heap-allocated memory is one of those cases, since you would need to de-allocate that memory when the owner is destroyed. Keeping additional book-keeping records, as a RefCell does would also disqualify it from implementing Copy since a simple bitwise-copy of the data would yield inconsistent or unusable results. Managing an external resource like an file handle is another case since you must coordinate with the OS to open() and close() the file explicitly.

Upvotes: 9

Miiao
Miiao

Reputation: 998

Clone trait provides clone method for copying. Stack or heap depends on implementation and type requirements. For example, if you’re cloning a String, copied value will be allocated in the heap. If you’re cloning a value of u8 type, copied value will be allocated on the stack. Copy trait does exactly what the Clone trait does, but implicitly.

If every cloned value was allocated in the heap, we wouldn’t need allocators 😔

Upvotes: -1

Related Questions