Re: A non-const reference may only be bound to an lvalue?
On Dec 17, 1:30 pm, Abhishek Padmanabh <abhishek.padman...@gmail.com>
wrote:
On Dec 17, 12:02 pm, George <Geo...@discussions.microsoft.com> wrote:
Thank Igor,
I think my question is almost answered. I want to finally confirm with you
that, the following code,
1. about how code works
template<typename T>
inline T&
lvalue_cast(const T& rvalue)
{
return const_cast<T&>(rvalue);
}
converts a rvalue to a lvalue, by changing const reference to a non-const
reference (removing const qualification on the variable). Because a non-const
reference is always a lvalue, so the code works and result in a lvalue (i.e.
a non-const reference).
2. about undefined behavior
Further operation on returned *lvalue*, e.g. assignment may result in
undefined bahavior. For example, if original rvalue is binded to a constant
sting. :-)
Are my both understanding (1) and (2) correct?
Yes, both correct. const_cast<> is just fine until you don't change
the object. In which case it is undefined behaviour as you noted in 2
above. const_cast<> should be rarely used for example with functions
(that you cannot change) that are not const correct i.e. you know that
they don't changed the passed object but don't accept them as const
arguments. Otherwise, there rarely is a need to use const_cast<>.
Actually, there is one more instance when you would use const_cast -
when you have overloaded functions of a class based on const-ness of
the function. You can implement the non-const function in terms of the
const version and you can apply the const_cast on the returned value
for example:
#include<vector>
template<typename T>
class A{
std::vector<T> vec;
public:
const T& operator[](size_t i) const
{
return vec[i];
}
T& operator[](size_t i)
{
return const_cast<T>( static_cast<const std::vector<T>
(vec)[i]);
}
};
Well, something like that... I think you get the idea.