C++ const_cast usage instead of C-style casts

后端 未结 4 1534
长情又很酷
长情又很酷 2021-01-17 23:51

Why is the following?:

  const int i0 = 5;
//int       i1 = const_cast(i0);       // compilation error
  int       i2 = (int)i0;                           


        
4条回答
  •  失恋的感觉
    2021-01-18 00:10

    According to CPP Reference, the result has to be pointer or references. When using pointer, the input also needs to be a pointer. For references, you can the variables as inputs, and reference as output. The page says:

    lvalue of any type T may be converted to a lvalue or rvalue reference to the same type T, more or less cv-qualified. Likewise, a prvalue of class type or an xvalue of any type may be converted to a more or less cv-qualified rvalue reference.

    meaning

    /* lvalue can be converted to lvalue or rvalue references  */
    int& test1 = const_cast(var);   // lvalue to l-ref; same works for class type
    int&& test2 = const_cast(var); // lvalue to r-ref; same works for class type
    /* prvalues: restriction on built-in types to allow some compiler optimization */
    //int&& test5 = const_cast(1);            // prvalue of built-in not allowed
    A&& test6 = const_cast(A());                // prvalue of class type allowed
    /* xvalue can be converted to rvalue references */
    int&& test8 = const_cast(std::move(var)); //xvalue of built-in
    A&& test8 = const_cast(std::move(A()));     // xvalue of class
    

提交回复
热议问题