Given the answers to the question Is the address of a reference to a dereferenced pointer the same as the address of the pointer? and my current understanding of references, I was very confused, when I checked the addresses of vector elements and compared them to the addresses of references to those elements:
#include <iostream>
#include <vector>
int main(){
std::vector<int> vec { 1, 2, 3, 4 };
const int&
ref0 { vec[0] },
ref1 { vec[1] },
ref2 { vec[2] },
ref3 { vec[3] };
std::cout
<< &(vec[0]) << " vs " << &ref0 << "\n"
<< &(vec[1]) << " vs " << &ref1 << "\n"
<< &(vec[2]) << " vs " << &ref2 << "\n"
<< &(vec[3]) << " vs " << &ref3 << "\n";
return 0;
}
Output on my machine (Ubuntu 20.04, compiled with g++ 9.3.0, default options):
0x561553dbdeb0 vs 0x561553dbdeb0
0x561553dbdeb4 vs 0x7fff539f4d6c
0x561553dbdeb8 vs 0x7fff539f4d70
0x561553dbdebc vs 0x7fff539f4d74
So the address of the first element and the address of the reference to the first element are the same, but all others are not. Why is that?