behaviour of const_cast

后端 未结 1 403
野性不改
野性不改 2021-01-15 20:08

I was reading about const_cast operator in c++

1.First weird thing thing i can\'t understand is

const_cast operator syntax i.e.

<
1条回答
  •  天涯浪人
    2021-01-15 20:52

    it helps to cast away constness of an expression of type Type

    No, Type is the type of the result, not the type of the operand.

    What i think is const of this pointer should be casted away

    this has type const ConstTest*. const_cast(this) has type ConstTest*. That's what "casting away const" from a pointer-to-const means.

    I feel code should have been ConstTest *c = const_cast(*this)

    The result of const_cast has type T, that's how it's defined. Maybe you would have defined it differently, but tough luck, you don't get a ConstTest* by writing const_cast, you get it by writing const_cast. Your preferred syntax is not available.

    You can either do ConstTest &c = const_cast(*this) or ConstTest *c = const_cast(this), so pick your favorite.

    The result of a const_cast expression is an rvalue unless Type is a reference type. In this case, the result is an lvalue.

    why so and why it is not true in case of pointers?

    It is true of pointers. ConstTest* is not a reference type, and the result of const_cast(this) is an rvalue. You then assign that value to the variable c.

    0 讨论(0)
提交回复
热议问题