Johannes Schaub - litb Johannes Schaub - litb - 9 months ago 51
C++ Question

Why does as_const forbid rvalue arguments?

I wanted to ask why

forbids rvalue arguments, according to (i.e. why the Standards folks made it so, not why specifically quoted them on that. And also not where in the spec the intent of the committee is codified, just for making sure :))). This (artificial) example would yield an error (user wants to make it const to keep COW quiet)

QChar c = as_const(getQString())[0];

Another question's answer notes that if we just remove the deletion of the rvalue reference overload, it would silently transform rvalues to lvalues. Right, but why not handle rvalues gracefully and return const rvalues for rvalue input and const lvalues for lvalue input?


One reason might be that it could be dangerous on rvalues due to lack of ownership transfer

for (auto const &&value : as_const(getQString()))  // whoops!

and that there might not be a compelling use case to justify disregarding this possibility.