我可以用stackoverflow确认我对C ++中的引用的理解是正确的。
假设我们有
vector<int> a;
// add some value in a
vector<int> b = a; // 1. this will result another exact copy of inclusive of a's item to be copied in b right?
vector<int> &c = a; // 2. c will reference a right? c and a both "point"/reference to a copy of vector list right?
vector<int> &d = c; // 3. d will reference c or/and a right? now a, c, d all reference to the same copy of variable
vector<int> e = d; // 4. e will copy a new set of list from d right (or you can say a or c)?
感谢。
答案 0 :(得分:4)
你是对的,b
是a
的独特副本,a/c/d
是完全相同的,只能通过不同的名称访问。
e
是a/c/d
的副本。
如果您使用int
类型而不是向量复制该代码,您可以通过地址查看正在发生的事情:
#include <iostream>
int main() {
int a = 7, b = a, &c = a, &d = a, e = d;
std::cout << "a @ " << &a << '\n';
std::cout << "b @ " << &b << '\n';
std::cout << "c @ " << &c << '\n';
std::cout << "d @ " << &d << '\n';
std::cout << "e @ " << &e << '\n';
return 0;
}
输出是:
a @ 0xbfaff524
b @ 0xbfaff520
c @ 0xbfaff524
d @ 0xbfaff524
e @ 0xbfaff51c
您可以看到a
,c
和d
在b
和e
不同时都具有相同的地址。
答案 1 :(得分:2)
如果您向c
或d
添加元素,新元素也会反映在a
中。
如果您将元素添加到e
,则仅 e
会有元素。