vendredi 16 décembre 2022

C++: Why can we bind elements in a vector returned by a function to non-const lvalue references?

I am new to move semantics and want to understand what's happening in this piece of code:

vector<int> create_vector() {
    return {0, 1, 2};
}

for (int &x : create_vector()) {
    /* ... */         
}

If I understand correctly, the function call create_vector() returns an rvalue. Therefore, the elements inside it should be rvalues as well (i.e. 0, 1, 2 are rvalues). However, in the range for loop, we are binding these rvalues to a non-const lvalue reference int &x, which shouldn't be allowed? I thought non-const lvalue references can only bind to lvalues, not rvalues.

What's happening here? Why is this allowed?

Aucun commentaire:

Enregistrer un commentaire