Incorrect initialization of a non-constant reference like 'int &', what is the reason?

I have a code that gets an error:

error: invalid initialization of a non-constant reference of type 'int &' from rvalue of type 'int' const int b = f (a ++); ^

int f(int& a)
{
    return a;
}

int main() {
    // your code goes here
    int a = 5;
    int b = f(a++);
    std::cout << b << std::endl;
    return 0;
}

What is the cause of this error?

+4
source share
3 answers

The postfix increment operator does not intreturn a temporary value. A temporary value cannot be associated with a reference to a non-constant lvalue, because changing this temporary value does not make sense. You are trying to associate a temporary with int&, which gives an error.

, pre-increment (++a), ( , const T&):

int f(int a)
{
    return a;
}
+1

.

- (a++) a a .

const? - , , const.

, , a++ ? ? ?

+5

:

int f(int& a)

. , (*).

- :

 - save current value as `r`
 - increment original variable
 - return `r`

, - , . :

int f(int a) //This will work
int f(const int& a) //And this

(*) constrcuts. , VC6:

struct T {};

void f(T& t)
{
}

int main()
{
    f(T());
}

.

+1

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


All Articles