Does Box::<str>::from("string slice") copy the content of the string slice?

Does Box::<str>::from("string slice") copy every characters from the original string slice to a new memory region or does it merely create a new pointer to the original memory region?

It copies the characters.

Looks to me like it creates a new allocation. Godbolt.

1 Like

That couldn't possibly work. The Box deallocates its buffer when dropped. It would be wrong (i.e., UB) to deallocate a pointer to a static string literal.

2 Likes

If you want an optionally allocated pointer to a str, you can use Cow<'static, str> (see Cow, and Playground example).

As @H2CO3 said, the Box will (unconditionally) deallocate when dropped, so it can't work with a plain Box.

However, you could create your own pointer-like type which achieves the same as Cow<'static, str> but using Box<str> instead of String for its owned variant. In either case, there will need to be a distinction on dropping at runtime which decides whether to deallocate.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.