Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ function return scope and reference

Tags:

c++

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.

like image 361
Code Keeper Avatar asked Feb 27 '23 10:02

Code Keeper


2 Answers

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.

like image 68
Omnifarious Avatar answered Mar 08 '23 09:03

Omnifarious


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).

like image 43
Greg Hewgill Avatar answered Mar 08 '23 08:03

Greg Hewgill