C ++: different output of automatic type between const int * and cont int &

Here are some sample code.

a. int ii = 0;
b. const int ci = ii;
c. auto e = &ci; --> e is const int *
d. auto &f = 42; --> invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int
e. const auto &g = 42 --> ok

Observation:
1. for item c) the type const is automatically determined 2. for item d) the type of const is not automatically determined 3. for the sentence e) the type of const must be added manually in order for it to work.

Why is type const automatically output for clause c but not d?

+4
source share
4 answers

The reason is not a constant, but a r-value.

You cannot take a non-constant reference to an r-value.

If you are interested in what r-value is, the original idea was something that could only be on the right side of the assignment.

, . , const.

:

  • c) ci const int, &ci const int.
  • d) 42 int. auto int, f int, r-
  • e) g - const int &, .
+7

, 42 const int, int. rvalue, , lvalue ( const), int. , auto .

ci 42, works:

auto &e = ci;
+1

auto &f = 42;

42 int, auto &f int &f. 42 , , r-. r , .

const auto &g = 42

g const int &, a const & .

0

, , . c - const. ci const int (int, const). &ci const int * ( int, ). int *, const.

, d rvalue ( "42" , . ?). e 42 , , .

0

Source: https://habr.com/ru/post/1609691/


All Articles