Re: A non-const reference may only be bound to an lvalue?



"George" <George@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote in message
news:65A40ADB-6FE8-4AC3-A562-AEF9579ACC71@xxxxxxxxxxxxx
In the following code,

template<typename T>
inline T&
lvalue_cast(const T& rvalue)
{
return const_cast<T&>(rvalue);
}

even if you tricks the compiler to make a const reference (rvalue) to
be a non-const reference (lvalue), I think there may be still risks.

Of course, as with any casts, it is unsafe and you are supposed to know
what you are doing. You are subverting the compiler's type safety, and
the responsibility for doing it correctly is on you.

For example, originally, rvalue const reference may be binded to some
constant, and if you converts (or tricks) it to *lvalue*, further
assignment to it through lvalue non-const reference will fail, right?

"Fail" in the sense that your program would exhibit undefined behavior,
yes. The program will still compile, and it may even run and appear to
do what you want (on some compilers under some circumstances).

So, I think the tricks or conversion does not actually converts a
rvalue to a lvalue, right?

The trick allows you to pass a temporary object where an lvalue is
normally required. You decide if you want to call it "conversion" or any
other name.
--
With best wishes,
Igor Tandetnik

With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925


.