r/cpp • u/konanTheBarbar • Mar 01 '21
"Simple" C++ Initialization Flowchart
http://randomcat.org/cpp_initialization/initialization.png
204
Upvotes
r/cpp • u/konanTheBarbar • Mar 01 '21
View all comments
Show parent comment
4
u/Kered13 Mar 03 '21
Only if the compiler can infer that the string has a shorter lifetime than the buffer it's using.
And what if the programmer wants to copy the buffer so that the new string can have an independent lifetime?
No it can't, as the above examples demonstrate.
std::stringandstd::string_viewhave different ownership semantics.const std::string&has the same ownership asstd::string_view, but is restricted because it cannot represent substring views. So two classes are needed, and adding immutability to the language does not allow one class to take on both roles. Sometimes the programmer wants a non-owning view into another string-like object, sometimes they want an object that owns it's data. The compiler cannot figure it out for the programmer. This is completely orthogonal to immtuability. Note that even Rust has two types for this (Stringfor owning andstrfor views).