calling non-static member function without instantiation using `reinterpret_cast`

主宰稳场 提交于 2019-12-11 13:58:43

问题


As it's shown in the following code, I can call a non-static member function A::f without instantiating an object of the class. This is only possible when the function is not bound to any other member. For example, I cannot call A::g in a similar fashion.

It seems to me that the call to A::f as shown in the code below behaves like calling a static member function. Is such a conclusion correct? How can this behavior be justified?

#include <iostream>
using namespace std;

struct A {
    void f() { cout << "Hello World!"; }    
    void g() { cout << i; } 
    int i = 10;
};

int main() {
    auto fPtr = reinterpret_cast<void(*)()>(&A::f);
    (*fPtr)(); // OK

//  auto gPtr = reinterpret_cast<void(*)()>(&A::g); 
//  (*gPtr)(); // Error!
    return 0;
}

回答1:


Is such a conclusion correct? How can this behavior be justified?

It's undefined behavior.

Pretty useless to ask for how it should specifically behave. Pick one or more from the list:

  • 2)Schroedingers cat is always found dead when you open the chest1
  • Your fridge explodes
  • You see the behavior you get
  • Little demons are flying out from your nostrils
  • 1)You get time warped back to the point, when you put the living cat into the chest2
  • ...
  • All of the above happens simultaneously

void f() { cout << "Hello World!"; }  

Well, the fact that your code doesn't rely on any member variable data makes it likely, that any decent implementation works without "crashing".

Though, it's simply UB to call a class member function without a valid class instance, as mentioned above.
So you can't predict what happens, or should rely on your observations.



来源:https://stackoverflow.com/questions/37579850/calling-non-static-member-function-without-instantiation-using-reinterpret-cast

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