behaviour of const_cast

霸气de小男生 提交于 2019-12-01 12:39:36

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<ConstTest*>(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<ConstTest>(*this)

The result of const_cast<T> 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<ConstTest>, you get it by writing const_cast<ConstTest*>. Your preferred syntax is not available.

You can either do ConstTest &c = const_cast<ConstTest&>(*this) or ConstTest *c = const_cast<ConstTest*>(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<ConstTest*>(this) is an rvalue. You then assign that value to the variable c.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!