C ++中的引用行为

时间:2013-08-28 07:36:49

标签: c++ reference

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

感谢。

2 个答案:

答案 0 :(得分:4)

你是对的,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

您可以看到acdbe不同时都具有相同的地址。

答案 1 :(得分:2)

是的,看起来没错。

如果您向cd添加元素,新元素也会反映在a中。 如果您将元素添加到e,则 e会有元素。