rvalue references: easy to get UB?
Hello All,
I have downloaded a recent version of g++ (4.3.2) which provides some
features from C++0x. I've been trying various things with rvalue
references, to see how they behave and get an intuition of what can be
done with them.
It seems to be easy to obtain a reference to a temporary that no
longer exists. Is this expected behavior (and thus UB), or should the
complier produce an error or warning?
If this is UB, could the problem be alleviated by increasing the
lifespan of "rvalue reference temporaries (RRT's)" to the end of the
block where the RRT was created? (Just a thought.)
Below is a program that uses rvalue references to bind temporaries to
references, in a function and a struct.
Thanks,
Derek.
/*********** file.cpp ************/
#include <iostream>
#include <cstring>
using namespace std;
// compiled with g++ (GCC) 4.3.2,
// g++ -Wall -std=c++0x file.cpp
string& Max(string&& a, string&& b)
{
if(a > b)
return a;
else
return b;
}
struct S
{
string&& n;
S(string&& nn):n(nn){}
};
int main()
{
string a = "aaa";
string b = "bbb";
string& m1 = Max(a,b);
string& m2 = Max(a, "ccc");
cout << "1:" << m1 << endl;
cout << "2:" << m2 << endl;
m1 += "?";
m2 += "!";
cout << "3:" << a << endl;
cout << "4:" << b << endl;
string ppp("ppp");
S p(ppp), q("qqq"), r("rrr");
cout << "5:" << p.n << endl;
cout << "6:" << q.n << endl;
cout << "7:" << r.n << endl;
}
/*******************
Output:
1:bbb
2:
3:aaa
4:bbb?!
5:ppp
6:
7:
*******************/
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]