Re: rvalue references: easy to get UB?
On Dec 11, 10:22 am, de...@antiquark.com wrote:
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.
Not too surprising. After all, temporaries are both rvalues, and,
well, temporary.
Is this expected behavior (and thus UB), or should the
complier produce an error or warning?
Given what you show below, it's expected.
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.)
I don't think that would be a good idea; it's inconsistent the way
regular references work to begin with.
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;
}
Change all your references above to string const& and you have the
exact same problem.
struct S
{
string&& n;
S(string&& nn):n(nn){}
};
That looks like it's asking for trouble. Change the references above
to string const& and you have the same problem. I don't think rvalue
references are really doing anything new here.
--
Dave Abrahams
BoostPro Computing
http://www.boostpro.com
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]