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:
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.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.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.
Local variables cannot be returned by reference.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With