Question

I find it curious that const_cast won't allow casting an rvalue (for example a temporary variable) to a const qualified reference, although it works just fine with a static_cast. Does anybody have an explanation about why it behaves this way?

const_cast< const std::string & >( std::string( "hello" ) ); // doesn't compile
static_cast< const std::string & >( std::string( "hello" ) ); // compiles

Please let's not get into the "const_cast is evil" argument, what I am trying to do here is properly understand the parts of the C++ standard that deal with const_cast and rvalues.

Was it helpful?

Solution

const_cast is specified to do very specific things. It can convert lvalues to lvalue references and rvalues to rvalue references. It can convert between pointers. It cannot convert from an rvalue to an lvalue reference, even a const one. Read 5.2.11 for the exact listing what the cast can do; what that section doesn't list, it can't do.

static_cast can do other things, as listed in 5.2.9. Among them, it can convert from rvalue to lvalue reference to const.

OTHER TIPS

const_cast can only add or remove constness. That's it. It can't do any other conversions (including from an rvalue to const lvalue reference, which your code sample involves).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top