user2919227
user2919227

Reputation: 41

why when i rebind the reference of c++ , the compiler doesn't report error

c++ primer 2.3.1 says : once initialized, a reference remains bound to its initial object . There is no way to rebind a reference to refer to a different object. But my code works well:

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

the running result is :

2

Upvotes: 2

Views: 136

Answers (1)

paddy
paddy

Reputation: 63481

You did not rebind. Instead, you assigned the value of b to a.

Check this yourself by printing out the addresses before and after that assignment:

std::cout << "a: " << &a << std::endl;
std::cout << "b: " << &b << std::endl;
std::cout << "r: " << &r << std::endl;

Upvotes: 7

Related Questions