4 ms·
Why should converting a &str to a String require memory allocation? It seems like String could just reference the &str and use COW?
by millstone 8y ago
Why should converting a &str to a String require memory allocation? It seems like String could just reference the &str and use COW?
- unrealhoang 8y agoThat source &str can be de-allocated before the String, and you need to track that through some kind of Rc. String is not just about mutability but also about ownership, if my function got a String, I know for sure after its execution, the memory will be released (if I don’t transfer the ownership back). I like this way much more. If in any case I need Cow, well, Rust has that in the standard library.
- GolDDranks 8y agoThat needs a garbage collector to work – the lifetime of String isn't limited, but the lifetime &str's is. That means that the backing storage of String can be deallocated under it's feet. There has been some discussion about allowing Strings to use COW in case of &'static str which doesn't have this problem, but I'm not sure whether that proposal has any momentum at the moment.
- pjmlp 8y agoIn C++ using COW for std::string was a common implementation approach, before C++11 made it invalid.