According to cppreference.com, when a const std::string is constructed from an input const char* (e.g. const std::string("some literal");), a copy of the C string is stored in the std::string.
I'm trying to understand if (and why) the copy is required specifically in the case where the input C string is a string literal. I would think that the std::string could simply refer to the string literal instead of creating a copy, so that the following code would only create "some literal" once.
std::string str1("some literal");
std::string str2("some literal");
Certainly, performing a copy for C strings that aren't string literals is wise, because it allows the std::string to manage the lifetime of the data that it refers to. However, this is not an issue for string literals because they exist for the lifetime of the program.
Also, since we are talking about const strings, we don't need to worry about the underlying data being changed during the program and breaking the value semantics of the std::strings. Well, at least as long as const_cast isn't used, but using const_cast is asking for trouble anyway, so I'm not too worried about that case.
So, is there any reason why the compiler can't optimize this case to have const std::strings refer to const char*s instead of creating copies? Alternatively, if the cppreference link was incorrect, and this optimization actually is implemented by some compilers, which compilers support this?
For the sake of this question, let's assume that the string literal is long enough that the small string optimization won't be a factor.