Why does "auto" declare strings as const char* instead of std::string?
The reason you can't "write" to your auto variable is that it's a const char * or const char [1], because that is the type of any string constant.
The point of auto is to resolve to the simplest possible type which "works" for the type of the assignment. The compiler does not "look forward to see what you are doing with the variable", so it doesn't understand that later on you will want to write into this variable, and use it to store a string, so std::string would make more sense.
You code could be made to work in many different ways, here's one that makes some sense:
std::string default_name = "";
auto name = default_name;
cin >> name;
Because string literals have type const char[N+1]
, not std::string
.
This is just a fact of the language.
They could have made it so that auto
has a special case for string literals, but that would be inconsistent, surprising and of very little benefit.
If you use string literals, auto
will work as expected.
In C++14, C++17 or C++20, you can place an s
after the quotes, and it will create a std::string
instead of a const char*
string.
This can be used together with auto
to create a std::string
:
auto hello = "hello"s;
String literals are not enabled by default. One way of enabling string literals is to place the following at the top of the source file:
#include <string>
using namespace std::string_literals;
As an example, this loop works for std::string
(with s
added to the string literal), but not for const char*
type string literals:
for (auto &x : hello) {
std::cout << "letter: " << x << std::endl;
}
Here is the cppreference page for the ""s operator.