Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does "auto" declare strings as const char* instead of std::string?

I made a template which adds the data it is given. If I use it like this, the compiler declares in_1 and in_2 as const char *, and the code doesn't compile.

#include <iostream>
using namespace std;
template <class T>
T addstuff(T part_1, T part_2){
    return(part_1+part_2);
}

int main(int argc, char const *argv[])
{
    auto in_1="Shut ";
    auto in_2="up.";
    cout<<addstuff(in_1, in_2)<<endl;
    return 0;
}

If I declare in_1 and in_2 std::string, it works like a charm.

Why can't (or doesn't) the compiler declare those strings automatically std::string?

like image 557
Magnus Avatar asked Jan 01 '14 14:01

Magnus


1 Answers

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;
like image 87
Yanshof Avatar answered Sep 21 '22 08:09

Yanshof