samedi 26 septembre 2020

Why is rvalue reference to an integer legal

This might be a dumb question about C++11 but it really bothers me.

As my understanding, rvalue reference is also a reference, which means that it will algo point to some variable, just like the reference does.

For example,

const int &ref = 1;

The reference ref points to the pure rvalue 1, which can't be modified, that's why the compiler force us to use const.

Another example,

Bar&& GetBar()
{
    Bar b;
    return std::move(b);
}

This function will return a dangling reference because b is destructed after returning.

In a word, rvalue reference is algo a reference.

Now I'm confused. Please check the following code:

int &&rref = 1;

If rvalue reference is also a reference, so rref now points to the pure rvalue 1, which shouldn't be compilable as my understanding, because if it's compilable, what if I execute rref = 2? Does this mean that the pure rvalue is changed: 1 becomes 2?

But gcc told me that it was compilable...

Why? Why don't we need const int &&rref = 1?

Aucun commentaire:

Enregistrer un commentaire