2

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?

RL-S
  • 734
  • 6
  • 21

1 Answers1

2

This is a simple typo: the & in the declaration only applies to ref0, the others are non-reference types!

Did you want

const int
        &ref0 { vec[0] },
        &ref1 { vec[1] },
        &ref2 { vec[2] },
        &ref3 { vec[3] };

This is more frequently fallen for with pointer declarations like int* p, q;.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • Right! I very rarely declare several variables in a row, so I forgot all about that! – RL-S Jul 13 '20 at 12:20
  • 1
    @RL-S: We've all done it! Perhaps it's an age thing, but I think it's easier to fall into this trap with references. I fixed an horrible bug due to this a few years ago. – Bathsheba Jul 13 '20 at 12:20