我可以通过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)?


谢谢。

最佳答案

没错,ba的唯一副本,a/c/d都是一样的东西,只是可以通过不同的名称访问。

ea/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


并且您可以看到acd都具有相同的地址,而be是不同的。

10-07 12:06