Returning a reference to temporary (built-in types)
It is clear from this stream that a string literal cannot be used for a function that returns a const string & as there is an implicit conversion from const char * to std :: string that creates a temporary one.
But then why am I getting a warning "warning: return reference to temporary" if my return type matches exactly and no conversion is needed, e.g .:
include <iostream>
const int& test(){
return 2;
}
int main(){
std::cout << test();
}
No implicit conversion is required for return value 2, so why is there a warning? I thought that using test () would be about the same as doing
const int& example = 2;
which is quite fair. Also, if I change 2 to 2.2 (so it's double) the program still works (with the same warning) even though there is a conversion from double to int? Should I be working with a problem similar to how const char * was returned to a string reference if there is a conversion from double to int?
source to share
The temporary is still created. In ยง8.5.3 / (5.2.2.2) 1 applies :
Otherwise, a temporary type "cv1
T1
" and copy-initialized (8.5) is created from the initializer expression. The link is then linked to a temporary one.
This also applies to your second example. It does not apply to prvalues โโof class type or scalar x: Both
const A& a = A();
// and
const int& i = std::move(myint);
do not enter temporary. However, this does not change the end result: in any case, the temporary associated with the link will be destroyed at the end of the statement return
- ยง12.2 / (5.2):
The lifetime of the temporary binding to the return value in a function expression
return
(6.6.3) does not extend; the temporary is destroyed at the end of the complete expression in thereturn
statement.
That is, the temporary is destroyed before the function even exits, and hence your program invokes undefined behavior.
1 I could go ahead and quote the entire list to show why he does this, but that would probably be a waste of space for an answer.
source to share
implicit conversion from const char * to std :: string that creates a temporary
You combine two themes. Implicit conversions are not the only thing that can create temporary ones:
const std::string& test() {
return std::string("no implicit conversions here.");
}
There is no implicit conversion to create string
, but the created one string
is still temporary and so you still return a reference to the temporary object.
In your example 2
, it is still a temporary value, temporarily stored somewhere on the stack, and whose location / address is returned so that callers can get the value, but they shouldn't.
source to share