Search code examples
c++stringreferenceoperator-keywordauto

why auto variable won't become reference when I use std::string::operator[]?


The std::string::operator[] should return char reference:

 char& operator[] (size_t pos);

But when I'm passing it to an auto type, it will become a simple char. Why won't it become a char& ?

I have the following code:

std::string str = "Hello";
auto strRef = str[1];

strRef = std::toupper(strRef);
std::cout  << "str after:" << str << std::endl;

On the output I will get "Hello" instead of "HEllo".


Solution

  • When you define the variable as non-reference and non-pointer, the reference part of the initializer will be ignored then strRef is deduced as char; the rule is same as template argument deduction.

    You need to declare it as reference explicitly.

    auto& strRef = str[1];