`impl<T: Copy> Copy for &mut T`?


If I write a struct:

struct Foo<T> { foo: T }

then Foo<T> will be Copy if and only if T is Copy.

Right now, &mut T is never Copy, always affine (move-only). This is because mutable aliasing in general can violate soundness, i.e. the iterator invalidation problem. But you clearly can’t violate soundness with, for example, a mutably aliased int.

What I’m wondering is whether we could, or should, do the same thing for &mut T as for Foo<T>, and say that it’s Copy iff T: Copy. This would essentially mean allowing things which are Copy (“plain old data”) to be mutably aliased. We already do this under controlled circumstances with Cell.

Doing this would have obvious benefits in terms of expressiveness. What negative aspects would it have? I don’t think it would compromise soundness (sketch of a proof: otherwise Cell would also be unsound). But it would involve losing some guarantees, e.g. right now, if you have an &mut int, you can know that nobody else can mutate that int but you. This would no longer be true (similar to &const).

EDIT: Here’s a more serious problem: it would also break the guarantee for &int, because you can borrow &mut int to &int. So &int would also behave like &const int. I’m liking this idea less now.

Has this idea been considered before?

cc @nikomatsakis



I am opposed to this because you can violate soundness with an &mut int by introducing data races. The plan is to use & and &mut for race freedom with a lightweight data parallelism API.



Sure. This was just brainstorming, not a direct proposal. Overall I don’t think I like it that much either - given a reasonable choice between more freedom or stronger guarantees (a.k.a. invariants), I would almost always opt for the guarantees.

But I do think this would be a legitimate option. Obviously it wouldn’t happen in a vacuum, and things which would rely on these guarantees might have to be ruled out (I’m assuming it wouldn’t currently violate soundness, only together with the plans for data parallelism?).


closed #4

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.