Code Keeper
Code Keeper

Reputation: 91

C++ function return scope and reference

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.

Upvotes: 4

Views: 637

Answers (4)

Greg Hewgill
Greg Hewgill

Reputation: 994717

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

Upvotes: 2

Omnifarious
Omnifarious

Reputation: 56098

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.

Upvotes: 4

Chubsdad
Chubsdad

Reputation: 25537

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()); 
}

Upvotes: 2

selbie
selbie

Reputation: 104589

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

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

Upvotes: 0

Related Questions