简体   繁体   中英

What happen when we assign a reference to a variable?

void func(){
    int a = 1;
    int b = a; // copy assignemnt
    int &c = a; // nothing?
    int d = c; // nothing?
}

For example, when we assign reference c to d , is there anything triggered (move, copy, etc.)?

What if d is an instance member? Is it safe to store a local variable reference into it?

when we assign reference c to d, is there anything triggered (move, copy, etc.)?

Your terminology's getting me confused! If you're talking about d and c , I assume you're referring to int d = c; I'd describe that as "assigning whatever c refers to to d ". "Assign reference c to d" sounds too much like int& c = d; .

Your code has:

int &c = a; // nothing?
int d = c; // nothing?

In the first line, nothing happens that you need to care about... c can be thought of as a nickname or alias for a . (At a hidden implementation level, it may or may not help to image c being an automatically-dereferenced pointer variable, and your int &c = a; being similar to int* p_c = &a; - it doesn't copy or move any int values around, nor change a in any way.)

In the second line, the variable d is assigned a copy of the value from a .

What if d is an instance member? Is it safe to store a local variable reference into it?

You're thinking of this the wrong way. When you assign to a member reference, you're assigning to the referenced object, and not the reference itself. The referenced object will be another int somewhere, and assignment from one int to another works as usual.

int &c = a;

c now refers to the same memory as the variable a . It doesn't matter where a is instantiated. When followed by

int d = c;

d gets the value in the memory referred to by c , that is, the same memory as a , Which contains a 1 . So now d==1 .

Since d is not a reference, it has its own memory (regardless of where that is) and its own value.

Of course, if you were instead to say

c = 2;

then the memory referenced by c (that is, the same memory as a ) is assigned the value 2 . So now a==2 . It also doesn't matter where a is declared; it's still assigned to 2 .

A reference creates an alias to another variable.

int &c= a; makes c an alias of a and int d= c; has the same effect as d= a;

A reference is safe, as its lifetime is shorter than that of the variable it points to.

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