In the following example, Foo is not doing what is intended, but I can’t figure out why this is allowed to compile.
#include <string>
#include <iostream>
typedef std::string& T;
T Foo(int & i)
{
return T(i);
}
int main()
{
int a = 1;
std::string & s = Foo(a);
}
I discovered this with templates, but the typedef shows that its unrelated to templates. Needless to say, s is not a valid string here. I would think that constructing the value in the return of Foo would produce a compile error.
What am I missing here?
First of all, it worth nothing that the problem actually has no relationship to templates because this code compiles a well:
The reason I think this compiles is that the
returnstatement is equivalent toin case
Thappens to be a reference members. … and this, of course, compiles: You promised you knew what you were doing and asked the compiler kindly to believe you.OK, found it at 5.2.3 [expr.type.conv] paragraph 1:
… and 5.4 [expr.cast] paragraph 4:
(the elisions cover cases involving user defined type, built-in type conversions,
constconversions, etc.)