开发者

Why is casting Derived** to Base*const* forbidden?

开发者 https://www.devze.com 2022-12-24 04:34 出处:网络
After reading this question, i saw the answer by Naveen containing a link to this page, which basically says, that casting from Derived** to Base** is forbidden since could change a pointer to an poin

After reading this question, i saw the answer by Naveen containing a link to this page, which basically says, that casting from Derived** to Base** is forbidden since could change a pointer to an pointer to a Derived1 object point to a pointer to a Derived2 object (like: *derived1PtrPtr=derived2Ptr).

OK, i understand this is evil ...

But when casting Derived** to Bas开发者_StackOverflow社区e*const* this is not even possible, so whats the reason that this is not allowed anyway ?


First thing is that, if you really need to, you can cast any pointer type to any other pointer type. For instance, you can cast to void* as an intermediate step.

Second, with pointers-to-pointers, it's not so much that there's a reason to make particular cases hard as that there are no special rules to make any particular cases easy.

Basically, you have a pointer to X - where X in your case happens to be another pointer. Some X cases get special treatment (e.g. derived classes can implicitly cast to bases) - but your X is not one of them. It's not the base class - it's a pointer. There are no implicit casts defined for derived**, other than to void* - you can't even implicitly cast derived** to void**.

I don't think the const has much to do with it in this case, though I could be missing something.


It's impossible to cast Derived** to Base** in the case of multiple inheritance. The base might live anywhere within the object, meaning the value inside the first pointer would need to be changed. And in your case, that pointer is even (becoming) const. So you need to introduce a new variable and assign.

In the likely case of single inheritance, I suppose reinterpret_cast would have defined behavior due to memory layout guarantees. Definitely something to think twice about though.

0

精彩评论

暂无评论...
验证码 换一张
取 消