2

static_cast では問題なく動作しますが、const_cast では右辺値 (一時変数など) を const 修飾参照にキャストできないことが不思議です。なぜこのように振る舞うかについて誰かが説明していますか?

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

「const_cast は悪」という議論には入らないでください。私がここでやろうとしていることは、const_cast と右辺値を扱う C++ 標準の部分を正しく理解することです。

4

2 に答える 2

3

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.

于 2014-03-03T13:05:38.153 に答える