A string literal is a pointer, so it's the same as passing e.g. the literal 1 to a function. The constructor takes that pointer by value, so it's simply copied and remains alive for the call of the function.
Oh! You're absolutely right. It's also mentioned in the notes on the cppreference page. I didn't realize the lifetime of string literals worked like this (though it makes perfect sense with them being char arrays), thank you for pointing out my mistake and teaching me something.
I'd still argue against using string_view in both cases, safety in the constructor and short string optimization in both. Though these arguments are subjective and you're completely correct about it not being undefined behavior, so the use of string_view here is not wrong.
5
u/Wurstinator Dec 08 '18
String literals are lvalues.
https://stackoverflow.com/q/10004511/1833497