-3

Example:

auto &h = 42;        // error:we can't bind a plain reference to a literal.
const auto &j = 42;  // right

I don't understand why compiler can't know &h is `const int& I mean ,"auto" is have two step:1.know what type of rvalue. 2.make sure lvalue become the type if the step is right,why we must add "const" when rvalue is literal?

wuduojia
  • 3
  • 2

1 Answers1

1

auto never deduces a const when the input was non-const. Since 42 has type int, then auto deduces to int and your code is equivalent to:

int& h = 42;

which is an error because a non-const lvalue reference cannot bind to a prvalue.

M.M
  • 138,810
  • 21
  • 208
  • 365