Why it is not possible to convert rvalues to lvalues? It is possible to do a conversion in the opposite direction though. Technically rvalues do have a memory address, isn't it?
You can:
int&& x = 3;
x
is now an lvalue. A so called 'rvalue-reference' can bind to a temporary,
but anything with a name is an lvalue, so you need to forward<>()
it if you need it's rvalueness back.
Note that by binding a temporary to a rvalue-reference (or a const reference) you extend its lifetime. Technically a cast is possible, but not recommended, since temporaries have short lifetime, so you typically get a dangling reference.
forward<>()
. –
Balkin x
to a function, func(x);
after that? –
Balkin It is rather straightforward to write a template function unmove()
, that does the opposite of std::move()
:
template<class T> T& unmove(T&& t) { return static_cast<T&>(t); }
Please note that, according to the standard since C++11:
a temporary bound to a reference parameter in a function call exists until the end of the full expression containing that function call: if the function returns a reference, which outlives the full expression, it becomes a dangling reference.
So it is safe to use unmove()
within a single full expression, but after the expression has been fully evaluated, the temporaries go away.
My common use for unmove()
is to call functions / methods, that return values through references, when I don't need those values.
o3tl
, that has the same purpose and same code as unmove
, except, that it is called temporary
there. The solution is simple to add an explicit static_cast
. Thanks for the pointer and I have already edited the answer. –
Femininity Correct an anwer above.
int&& x = 3;
x
is 'rvalue-reference'. See
https://www.tutorialspoint.com/What-is-double-address-operator-and-and-in-Cplusplus
x
, and "lvalue" is the value-category of x
. There is no such value-category as "rvalue-reference". –
Laudian x
is an lvalue of type int
, while variable x
has type int &&
, aka "rvalue reference to int" (not an rvalue, since only expressions can be rvalues/lvalues/etc). –
Cataplasm © 2022 - 2024 — McMap. All rights reserved.
int x = 1;
-- 1 is an rvalue here. Does the literal 1 have a memory address? Can you do&1
to obtain its address? – Sensillumconst int& bon = 2;
possible then? – Moccasinbon
then referring to, address-wise? – Moccasinint
object -- this temporary has an obtainable address only after it is bound to a reference. – Sensillumconst int& bon = 2;
, the compiler creates a temporary integer that is assigned the given literal at the right-hand-side of the assignment statement. This temporary, in opposite to the literal, has an address that assigned to the const reference anddd the temporary then has a life time equal to the reference. Did I get it right? I really appreciate your time bud, :)) @Sensillum – Moccasin&*"hello"
? – Psycholinguistics