Re: rvalue references: easy to get UB?
On Dec 11, 11:59 pm, Rodrigo <rcc.d...@gmail.com> wrote:
This was explained in depth here:http://groups.google.com/group/comp.lang.c++.moderated/browse_thread/...
Thank you.
Probably not. If the function is not inlined I think its not possible:
// file1.cpp
string&& weird(string&& a, string&& b)
{
return ((std::rand( ) == 1)? a : b);
}
//file2.cpp
string&& c = weird("a", "b"); // which temporary should have its
lifespan increased?
How about this hack: any rvalue reference temporary (RRT) will be
converted to a static variable by the compiler? So your example would
be rewritten as:
static string rvalref_temp_1; rvalref_temp_1 = "a";
static string rvalref_temp_2; rvalref_temp_2 = "b";
string && c = weird(rvalref_temp_1, rvalref_temp_2);
In effect, you make the lifespan of RRT's eternal! That would allow
them to be called from within functions too:
string& MoreWeird(string&& a)
{
return weird(a, "lalala");//must increase lifespan of "lalala"
}
This would be rewritten as:
string& MoreWeird(string&& a)
{
static string rvalref_temp_1; rvalref_temp_1 = "lalala";
return weird(a, rvalref_temp_1);
}
It would be nice if this aspect of rvalue references were cleaned up,
it would allow some really concise and useful code, e.g, you could
write a single function:
template<class T>
T& RefToMin(T&& a, T&& b)
{
if(a < b)return a; else return b;
}
That you'd otherwise have to overload because RRT's have a short
lifespan.
Derek.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]