隐藏的 G++ 引用错误

hidden g++ reference error

本文关键字:错误 引用 G++ 隐藏      更新时间:2023-10-16

使用 GCC 4.8.1 (MinGW) 编译,命令:g++ -o test.exe test.cpp

测试.cpp

#include <iostream>
int a = 1, b = 2;
void F()
{
    int &r = a;
    std::cout << r;
    r = b;
    std::cout << r;
}
int main ( int, char** )
{
    F();
    F();
    return 0;
}

预期输出为:1212,但实际为:1222

r定义为指针时,它按预期工作。

void F()
{
    int *r = &a;
    std::cout << *r;
    r = &b;
    std::cout << *r;
}

有人知道"帐篷里的钥匙"在哪里吗?

在带有指针的示例中:

r = &b;

这将重新放置指针r指向b。 在带有引用的示例中:

r = b;

您可能认为这类似于带有指针的示例,但事实并非如此。 引用不能像指针那样重新拔插。一旦它们被初始化,它们就会成为它们所引用的事物的别名。 所以上面的一行完全等同于这个:

a = b;

也就是说,它将存储在b中的值复制到a

参考示例可以这样写:

void F()
{
    std::cout << a;
    a = b;
    std::cout << a;
}

虽然指针示例可以这样写:

void F()
{
    std::cout << a;    
    std::cout << b;
}

您的"问题"是以下行:

int &r = a;

这将创建一个指向a的所谓引用。虽然引用在访问它们时不需要额外的逻辑(即取消引用;与指针相比),但它们在后台仍然以相同的方式工作。

所以一旦你上线

r = b;

您将实际使用该引用并更新 a 的值。在这种情况下,r从来没有自己的价值。它将始终指向a,并且本质上是一个别名。

在第二个示例中,这是不同的。该行

int *r = &a;

创建一个指向a

r = &b;

将重新分配该地址,使指针现在指向 b

简而言之,当您为指针分配其他值(地址)时,您更改指针,它将指向其他地方。但是,在为引用分配新值时,您实际上是在更新它所引用的初始而不是引用本身

//global variables! remember that this will be like a state
//and will be freed on (data?BSS?stack?) only after end of program.
int a = 1, b = 2;
void F()
{
    //You are referencing here,
    //meaning, once you change the referee ( r )
    //the reference will changed permanently.
    //Permanently because you are referring to a global variable.
    int &r = a;        
    std::cout << r;
    //You have changed the value of ( r )
    //forever!
    r = b;   //I think you are assuming the you have changed the reference address here?
    std::cout << r;
}

void F()
{
    //You have declared and initialized a pointer
    //that points to global variable.
    //w/c means you can also change its value forever!
    int *r = &a;
    std::cout << *r;
    //You have changed the ( r ) address pointing to, not its value!
    r = &b;
    std::cout << *r;
}
Your code is absolutely fine and it's working according to your instruction.
Suppose a variable has 1000 address b variable 1004 address, now your first line is  
         int &r = a;
that means r has 1000 address  and you did cout<< r //print 1
In second statement  r = b that means 1000 address hold value of b means 2;
Now , your scenario has been changed 1000---> 2 and 1004--->2 
and again you are calling F();
that's why compiler print twice 2 value. . There is a concept referencing in c++. Hope it  
would be useful for u