Re: Temporary objects, l-values.
Erik Wikstr?m wrote:
On 2008-02-19 11:36, jason.cipriani@gmail.com wrote:
If you can call the assignment operator on a temporary, why are you
not allowed to bind temporaries to non-const reference parameters? I
mean, code like this *seems* entirely reasonable to me:
void function (A &a) {
// do some stuff to a here
}
void function2 (void) {
function(A());
}
Why is that illegal? You create a new A(), pass a reference to it to
function (so it's not copied when you call function(), it's created
before the actual call is made), it's valid inside function(), you
can do stuff to it, function() returns, statement ends, A() is
destroyed. It doesn't seem dangerous, unpredictable, indeterminant,
or anything. Do you know why you aren't allowed to do that, then
(mostly for my own curiosity, I don't actually have a program that I
"need" to do something like that in)?
And since temporaries are not necessarily const, why can they (even
the non-const ones) only be bound to const references?
While it would work to allow to bind (non-const) references to temporary
objects in the above code it would not work in many other situations
that would also be allowed. Consider the following:
class Foo {
int i;
public:
void print() {
std::cout << i << std::endl;
}
};
void bar() {
Foo& f = Foo();
f.print();
}
In this example f is referring to a non-existing object when pring() is
called (it is a so called dangling reference). Binding temporaries to
const references is a special rule in C++, what happens is that the life
of the temporary object is extended to be as long as the life of the
reference it is bound to.
That is not entirely correct. The standard says [12.2/4-5]:
There are two contexts in which temporaries are destroyed at a different
point than the end of the fullexpression. The first context is ...
The second context is when a reference is bound to a temporary. The
temporary to which the reference is bound or the temporary that is the
complete object to a subobject of which the temporary is bound persists
for the lifetime of the reference except as specified below.
and then a list of exceptions to the rule follows. Note that the life-time
extension does not depend on the constness or non-constness of the
reference. In particular, if [8.5.3/5] was worded to allow temporaries to
bind to non-const references, your code snippet would be perfectly fine.
Best
Kai-Uwe Bux