4

I was writing a library for a generic Box<T> and on one part of the code I needed to clone the Box<T>, so I did something like this:

impl<T> OnTheFlySwap<T> where T: ?Sized + Send + Sync, Box<T>: Clone { 

I added Box<T>: Clone thinking this is not a big deal, because only objects that explicitly prohibits Box<T>: Clone would have a problem. But no, apparently if the object does not explicitly implements Box<T>: Clone then I have a problem, because this is the official impl Clone for Box:

impl<T, A> Clone for Box<T, A> where T: Clone, A: Allocator + Clone, 

It requires T to be Clone. Why? Wouldn't every Box<T> be Clone, since cloning a Box requires no time? If an object does not want its box to be clone then it could implement !Clone for it, but the default should be impl Clone for Box<T> for any T.

2
  • 1
    since cloning a Box requires no time? What makes you think cloning has to do with time? Cloning has to do with if an object can, well, make a clone of itself. Are you thinking of something like Rc that can clone itself independent of the inner object? Commented Jun 27, 2021 at 4:01
  • 1
    Indeed, the concept you have in mind is named Rc in Rust, not Box. In fact, Rc<T> is Clone for all types T. Commented Jun 27, 2021 at 8:31

1 Answer 1

13

A Box<T> in Rust represents a box which owns a T. If you could clone a Box and get a second box pointing to the same T, then which one would own the T value? Box isn't just Rust's version of C++ pointers; it represents a concept of ownership that a language like C++ doesn't enforce.

As an exercise, consider trying to write the function you're suggesting for Box::clone yourself. Its signature would be

fn my_clone<T>(value: &Box<T>) -> Box<T> { ... } 

Try writing a function with that signature without dipping into unsafe. The compiler will let you know pretty quickly what went wrong.

The only safe way to clone a box is to clone everything inside of the box as well, and that requires T : Clone.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.