调用非静态成员函数而不使用`reinterpret_cast`实例化 [英] calling non-static member function without instantiation using `reinterpret_cast`
问题描述
如下面的代码所示,我可以调用非静态成员函数 A :: f
而不实例化该类的对象。仅当函数未绑定到任何其他成员时,才有可能。例如,我不能以类似的方式调用 A :: g
。
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.
在我看来,对 A :: f
的调用如下面的代码所示静态成员函数。这样的结论正确吗?
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;
}
推荐答案
这样的结论正确吗?
Is such a conclusion correct? How can this behavior be justified?
这是未定义的行为。
问它应该如何特定表现几乎没有用。从列表中选择一个或多个:
Pretty useless to ask for how it should specifically behave. Pick one or more from the list:
- 2)打开箱子的时候总是发现Schroedingers猫死了 1
- 冰箱爆炸
- 您看到的行为
- 小恶魔从你的鼻孔飞出
- 1)当你把活猫放到胸前时,时间会扭曲回到原来的位置 2
- ...
- 以上所有内容同时发生
- 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".
尽管如此,调用类成员只是UB函数,而没有有效的类实例,如上所述。
因此,您无法预测会发生什么,或者应该依靠自己的观察结果。
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.
这篇关于调用非静态成员函数而不使用`reinterpret_cast`实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!