Re: Temporaries
Francesco wrote:
On Aug 12, 6:17 pm, Prasoon <prasoonthegr...@gmail.com> wrote:
Are all temporaries in C++ "rvalues"?
According to me "yes".
Am I right?
However consider the following code.
#include <iostream>
int a;
int& foo()
{
return a;
}
int main()
{
foo()=6;
}
Is there any temporary created in the above code?
According to me "no" there isn't any.
foo() returns just a reference to "a" (and no temporary created).
Correct me if I am wrong.
I don't know how my code would fit into the discourse that follows to
your post, Praason, anyway, the following...
-------
#include <iostream>
using namespace std;
struct temp {
string id;
void operator=(int i) {
cout << id << ": " << i << endl;
}
};
temp operator+(temp t, string s) {
temp res;
res.id = t.id + s;
return res;
}
int main()
{
temp t;
t.id = "t";
(t + "_temp") = 6;
return 0;
}
-------
...does compile and produces this output:
t_temp: 6
Hence I assume that the expression:
(t + "_temp")
turns into a temporary object which seems an lvalue to me.
It's not an lvalue, although its position on the left side of the
assignment expression would suggest that. What we see here is that it's
a modifiable rvalue, and the non-const member function (your operator=
with 'int' as the argument in that case) is called for it. That's
explicitly allowed by the Standard (you can find it in [basic.lval]/10.
The expression in the penultimate statement in 'main' can be rewritten as
(t + "_temp").operator=(6);
which makes it more apparent that a non-const member function is called
to modify the temporary object.
But please don't ask me to defend my statement: it's just an
impression, and I could have misunderstood what an lvalue actually is.
Happens. C++ stretches the meaning of rvalue and lvalue (as Alf
explained elsethread).
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask