Beginner question.
In the following code, I was expecting v2[0]=1
would also change the value of v1
, but it seems not.
push_back
seems to receive T&&
since C++11(ref), and std::move
is equivalent to static_cast<T&&>(t);
according to this answer. Also std::vector::operator[] returns reference(ref).
So I thought v2.push_back(std::move(v1[0]));
would make a reference to the same value.
What am I missing here? I thought the output would be 1
and 1
.
#include <iostream>
#include <vector>
int main(){
std::vector<int> v1{5}, v2;
v2.push_back(std::move(v1[0]));
v2[0] = 1;
std::cout << v1[0] << '\n';
std::cout << v2[0] << '\n';
// output:
// 5
// 1
}