1

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".

Mat
  • 461
  • 4
  • 14

1 Answers1

4

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];
songyuanyao
  • 169,198
  • 16
  • 310
  • 405