Skip to content

Clarify that RFC1520 does not permit the compiler to replace calls to Clone::clone with a memcpy #3197

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 13 additions & 7 deletions text/1521-copy-clone-semantics.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
# Summary
[summary]: #summary

With specialization on the way, we need to talk about the semantics of
`<T as Clone>::clone() where T: Copy`.
Clarify semantics of `Clone` so that users are permitted to assume that
`<T as Clone>::clone() where T: Copy` is implemented by `memcpy`.

It's generally been an unspoken rule of Rust that a `clone` of a `Copy` type is
equivalent to a `memcpy` of that type; however, that fact is not documented
Expand All @@ -34,15 +34,21 @@ compatible to upgrade to Clone in the future if demand is high enough."
# Detailed design
[design]: #detailed-design

Specify that `<T as Clone>::clone(t)` shall be equivalent to `ptr::read(t)`
where `T: Copy, t: &T`. An implementation that does not uphold this *shall not*
result in undefined behavior; `Clone` is not an `unsafe trait`.
Specify that users may assume `<T as Clone>::clone(t)` to be equivalent to
`ptr::read(t)` where `T: Copy, t: &T`. An implementation that does not uphold
this *shall not* result in undefined behavior; `Clone` is not an `unsafe
trait`.

Also add something like the following sentence to the documentation for the
Also add something like the following paragraph to the documentation for the
`Clone` trait:

"If `T: Copy`, `x: T`, and `y: &T`, then `let x = y.clone();` is equivalent to
`let x = *y;`. Manual implementations must be careful to uphold this."
`let x = *y;`. Implementors *should* be careful to uphold this invariant, as
consumers *may* assume that it holds (though `unsafe` code **must not** rely on
it holding as a precondition for memory safety). Note that the compiler itself
*will not* assume that the invariant holds when compiling calls to
`Clone::clone`, thereby guaranteeing that the relevant `clone` method will be
invoked."

# Drawbacks
[drawbacks]: #drawbacks
Expand Down