recently I am learning C++ and have some doubt on the following case.
void function_a(const int &i){
//using i to do something
}
int function_b(){
return 1;
}
ok, if I am going to call...
function_a(function_b());
is there any chance that function_a read dirty reference from the it's param?
Thank for your time.
No, there is no chance this will fail. The temporary created by the return of function_b
is guaranteed to remain in existence at least until the end of the statement.
In this case, the compiler will generate an unnamed temporary value whose reference will be passed to function_a
. Your code will be roughly equivalent to:
int temporary = function_b();
function_a(temporary);
The scope of temporary
lasts until the end of the statement that calls function_a()
(this is inconsequential for an integer, but may determine when a destructor is called for a more complex object).
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