C++ function return scope and reference
recently I am lear开发者_JS百科ning 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).
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());
}
The question is moot. That type of operation won't compile.
error C2664: 'function_a' : cannot convert parameter 1 from 'int' to 'int &'
精彩评论