jeudi 26 avril 2018

Inexplicable behaviour of the function accepting an universal reference and returning a const reference

I have always thought that the following function, which accepts an universal reference, must return a const-reference.

template <typename T>
const T& Const(T&& val)
{
    return val;
}

However, the following code compiles successfully with VS C++ and gcc:

int x = 5;
Const(x) = 6;

The value of the variable x is equal to 6 after the run. Thus, the Const function returns a non-const reference.

To obtain a compiler error, the function Const must be modified either to accept a conventional l-value reference or to be declared as returning const std::remove_reference_t&.

Why is that? What rule did I miss? Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire