向量元素的引用地址与其指向的向量元素具有不同的地址。为什么?
Address of reference to a vector element has different address than the vector element it points to. Why?
鉴于问题Is the address of a reference to a dereferenced pointer the same as the address of the pointer?的答案和我目前对引用的理解,当我检查向量元素的地址并将它们与引用这些元素的地址进行比较时,我感到非常困惑:
#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;
}
我机器上的输出(Ubuntu 20.04,用 g++ 9.3.0 编译,默认选项):
0x561553dbdeb0 vs 0x561553dbdeb0
0x561553dbdeb4 vs 0x7fff539f4d6c
0x561553dbdeb8 vs 0x7fff539f4d70
0x561553dbdebc vs 0x7fff539f4d74
所以第一个元素的地址和第一个元素的引用地址是一样的,其他的都不一样。这是为什么?
这是一个简单的错字:声明中的&
只适用于ref0
,其他都是非引用类型!
你要吗
const int
&ref0 { vec[0] },
&ref1 { vec[1] },
&ref2 { vec[2] },
&ref3 { vec[3] };
这更常被像 int* p, q;
.
这样的指针声明所误导
鉴于问题Is the address of a reference to a dereferenced pointer the same as the address of the pointer?的答案和我目前对引用的理解,当我检查向量元素的地址并将它们与引用这些元素的地址进行比较时,我感到非常困惑:
#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;
}
我机器上的输出(Ubuntu 20.04,用 g++ 9.3.0 编译,默认选项):
0x561553dbdeb0 vs 0x561553dbdeb0
0x561553dbdeb4 vs 0x7fff539f4d6c
0x561553dbdeb8 vs 0x7fff539f4d70
0x561553dbdebc vs 0x7fff539f4d74
所以第一个元素的地址和第一个元素的引用地址是一样的,其他的都不一样。这是为什么?
这是一个简单的错字:声明中的&
只适用于ref0
,其他都是非引用类型!
你要吗
const int
&ref0 { vec[0] },
&ref1 { vec[1] },
&ref2 { vec[2] },
&ref3 { vec[3] };
这更常被像 int* p, q;
.