tags:

views:

119

answers:

4

Hi, 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.

+2  A: 

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

Greg Hewgill
Is that true? I always thought that `return 1` returns a left-hand constant that is immutable.
Delan Azabani
@Delan Azabani: The original question has been updated to include `const`.
Greg Hewgill
@Delan Azabani: `int foo();` actually is an *rvalue* expression (r, not l)
David Rodríguez - dribeas
Really? That's unexpected for me, but I guess we all learn something daily ;)
Delan Azabani
A: 

The question is moot. That type of operation won't compile.

error C2664: 'function_a' : cannot convert parameter 1 from 'int' to 'int &'

selbie
I am sorry, I forget the const in the function_a param.
Smile Programming
+2  A: 

You need to write as below.

'i' cannot bind to a temporary returned from 'function_b'. There is no issue about a dirty reference here as a 'temporary' is involved here rather a reference to a function local (which goes out of scope once 'function_b' returns)

void function_a(int const &i){ 
  //using i to do something 
} 

int function_b(){ 
  return 1; 
}

int main(){
   function_a(function_b()); 
}
Chubsdad
Thanks for your reminder.Is the temporary of the 'i' safe inside the scope of function_a ?
Smile Programming
yes. the temporary is safe until the full expressionfunction_a(function_b());
Chubsdad
I am going to read books again, thank you.
Smile Programming
+4  A: 

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.

Omnifarious