Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning reference argument to local variable

Tags:

c++

reference

Does the following code invoke any type of implementation-defined or undefined behavior? I'm unsure how the interaction with the reference is working and my Google/SO searches are coming up empty:

struct S {
    int i;
};

void Fn(S& s_arg) {
    S s_fn{s_arg.i+1};
    s_arg = s_fn;
}

int main(int argc, char** argv) {
    S s_main{15};
    Fn(s_main);
    return 0;
}

I'm unsure which of the two should occur when the assignment occurs in Fn:

  1. The default copy assignment operator of S is invoked on s_main (being the target of the s_arg reference), copying the data from the local (to Fn) s_fn into main's local s_main (via the s_arg reference, making everything proper and well-defined.
  2. The reference itself is assigned and now refers to Fn's local s_fn. Fn is now returning a reference to local data and the program is now just waiting for another function to be called from main, overwriting Fn's local s_fn and causing general mayhem.
like image 815
user2555367 Avatar asked Jul 06 '13 01:07

user2555367


People also ask

How do you assign a reference to a variable?

To assign reference to a variable, use the ref keyword. A reference parameter is a reference to a memory location of a variable. When you pass parameters by reference, unlike value parameters, a new storage location is not created for these parameters. Declare the reference parameters using the ref keyword.

Can you return a reference to a local variable?

Local variables cannot be returned by reference.

What happens when you assign a reference to a variable?

It's like an alias for existing variable. This means that the original variable and the reference both refer to same value and the real beauty of a reference lies in the fact that you can do the same operations on the value through a reference as you could do with the original variable.

Can you assign a reference to a variable C++?

C++ References. C++ references allow you to create a second name for the a variable that you can use to read or modify the original data stored in that variable.


1 Answers

There is no UB here, the reference points to s_main and you are assigning to the value of s_fn to s_arg (which is pointing to s_main) and all is well. Remember that references (unlike pointers) once initialized cannot point to another region in memory which means the second case you mentioned cannot happen.

like image 188
Borgleader Avatar answered Sep 25 '22 17:09

Borgleader



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!