C++ - 为什么对同一对象的 2 个本地引用保持同步?

C++ - Why does 2 local references to the same object stay in sync?

我想了解这里发生了什么。显然,我对引用或赋值运算符的某些方面理解不正确。

Objective:在一个函数中,我想对同一个列表的不同元素使用 2 个局部引用变量:一个是迭代,一个是a "marker" 在满足特定条件时发生变化。两者最初都引用相同的元素。我没有修改列表中的字符串(在实际代码中,列表是通过引用传递的参数)。

问题:一旦将第二个引用更改为另一个元素,第一个引用现在也指向该新元素。引用保持同步,但我希望它们是独立的。

我的解释:迭代器是指向包含在列表中的字符串的指针。在 string & ref1 = *it 中,我取消引用迭代器指针以获取字符串地址(IMO 本身是否是指针并不重要),因此 ref1ref2 是 "aliases"到字符串 "a" 的地址。所以在我看来,更改 ref2 使其指向另一个字符串不会更改任何内容的地址,但 ref2 的值现在应该或 "alias" 指向字符串 "b",而 ref1 仍应指向"a".

将代码更改为使用指针而不是引用非常有效,所以我似乎错误地将引用变量视为指针,或者在幕后有一些东西(重载赋值运算符?)我没有想到。

list<string> l;    
string s1 = "a";   
string s2 = "b";    
l.push_back(s1);    
l.push_back(s2);    
list<string>::iterator it = l.begin();    
string & ref1 = *it;    
string & ref2 = *it;    
++it;    // After this line, both ref1 && ref2 evaluates to "a"
ref2 = *it; // After this line, both ref1 && ref2 evaluates to "b"
if(ref1 == ref2){    
  cout << "woot!" << endl;    
}
string & ref1 = *it;    
string & ref2 = *it;

好的,所以您创建了对同一字符串的两个引用。

++it;    // After this line, both ref1 && ref2 evaluates to "a"

对,因为它们都是对同一个字符串的引用。这就是您创建它们的方式。

ref2 = *it; // After this line, both ref1 && ref2 evaluates to "b"

是的,因为它们都是对同一个字符串的引用,而您只是用一个来更改它所引用的字符串的值。

So in my mind, changing ref2 so it points to another string does not change the address of anything, but just the value of ref2 should now point or "alias" to string "b", while ref1 should still points to "a".

引用不是这样的。引用是这样工作的:

int a, b;
int& ref = a;
ref = b; // same as a=b, does not "re-seat" the reference

如果您想要一个可以是 "re-seated" 的引用,请使用 std::reference_wrapper

引用类似于指针,您不能更改它指向的地址。分配给引用与分配给它指向的地址相同,而不是分配给指针:

int x = 5;
int& xref = x;
// equivalent to:
int* const xptr = &x;

xref = 10;
// equivalent to:
*xptr = 10;