有人可以向我解释什么是"reference reseating",为什么"a reference to point(refer) to another object"不可能?

Can somebody explain to me what is "reference reseating", and why is it not possible for "a reference to point(refer) to another object"?

本文关键字:to reference point refer 不可能 object another 可以向 解释 什么 reseating      更新时间:2023-10-16

根据这些链接:stackoverflow问题和C++FQA引用一旦初始化就不能很好地引用另一个对象/变量,但下面的代码呢?

// Example program in C++
#include <iostream>
using namespace std;
int main()
{
    int x=10, z=12;
    int &y=x;
    ++y;
    y=z; //valid?
    cout << x << ", "<< y <<", " << z << endl; // prints 12, 12, 12
    return 0;
}

下面是关于指针重新定位的C代码,它似乎是有效的,对吗?

#include <stdio.h>
int main(int argc, char *argv[])
{
    int a=10, b=20;
    int *ptr;   
    ptr = &a;
    ptr = &b;
    printf("%dn",a); // prints 10
    printf("%dn",*ptr); // prints 20
    return 0;
}

有人能在以上两个代码中澄清上述概念吗?

y=z; //valid?

当然!但这并不意味着"y从现在起就是z"。意思是"将z的值设置为y当前所指的值",即x。因此,y=zx=z的另一种书写方式。

下面是关于指针重新定位的C代码,它似乎是有效的,对吗?

与引用不同,指针可以重新指向,因此指针的重新分配使其指向不同的变量。然而,您的程序并没有说明这一点,因为对ptr的两个赋值在其间没有任何对ptr的读取,所以只有第二个赋值保留下来。

y=z

它不引用另一个变量,它只是将z的值分配给y,即12,并且由于y引用了x,所以x也得到了分配的值12。

所以x=y=z=12

但在指针中,更改其指向的地址是有效的:

ptr = &a;
ptr = &b; //valid
相关文章: