Why is it allowed to static_cast a method of a derived class to a method of the base class?

核能气质少年 提交于 2020-01-24 19:33:10

问题


example

struct B1{int x; void f(){x = 1;}};
struct D : B1{int x; void f(){B1::x = 2;}};

using Dmp = void(D::*)();
using B1mp = void(B1::*)();

int main()
{
    Dmp dmp = &D::f;
    D d;
    (d.*dmp)(); // ok

    B1mp b1mp = static_cast<B1mp>(dmp); // hm, well that's weird
    B1 b1;
    (b1.*b1mp)();

    dmp = &B1::f; // ok
}

And this example will compile and run just fine, and no problem will arise. But wait, now I'm going to use D::x in D::f, and now -- anything can happen at runtime.

Yes, you can also static_cast a pointer to the base to a pointer to a derived.

static_cast<D*>( (B1*)0 )

But here you can use RTTI to check the types, or just use dynamic_cast if possible.


回答1:


Yes, static_cast allows a number of things that might be used in "unsafe" ways, like converting void* to another object pointer type, converting Base* to Derived*, and this one.

Although static_cast can be thought of as "relatively safe" compared to reinterpret_cast and const_cast, it's still a cast. And like all casts, it represents a request to ignore some of the type system's safety requirements, with the programmer then responsible for using it carefully and correctly.




回答2:


In

void f(B *b) {
  static_cast<D*>(b)->d_method();
  b->static_cast<void (B::*)()>(&D::d_method)();
}

you assume that b is a D to exactly the same degree in each case. Being able to cast the pointer-to-member allows a caller to nominate any function from any derived class when passed to a function that expects a pointer-to-member for the base.



来源:https://stackoverflow.com/questions/59228652/why-is-it-allowed-to-static-cast-a-method-of-a-derived-class-to-a-method-of-the

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