简体   繁体   中英

Can Lvalue Reference be bounded to Rvalue Reference? What will happen during the process?

I am trying to figure out the meaning of the following snippet:

int main() {
    int&& a = 2;
    int& b = a;     // (*)
}

I know a is an lvalue expression of type "rvalue reference to int ", and b is a general variable with type "lvalue reference to int ". However, the initialization (*) of b seems weird. Since the type of a is not an int , it cannot match the type that b refers to. Can anyone explain this result? Is there any implicit conversion happening during the initialization (*) ? Or is there any concept or keyword that I missed?

The code can be compiled and run successfully in here .

Any reference acts as if it's the referred object. Thus when you bind a reference b to another reference a , you actually bind it to the object a refers to.

One tricky part is that rvalue reference is an lvalue itself and C++ allows you to bind only lvalue reference to lvalues, thus you won't be able to bind another rvalue reference here:

int&& a = 2;
int&& b = a; // error

Another notable side-effect, is that a in your sample extends the lifetime of the temporary to the end of the given scope (to be precise to the end of a reference lifetime)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM