[英]How does casting this pointer to an unrelated class work?
This confuses me because if "this" points to its own object, how would casting it ( without inheritance ) allow me to access other class members?这让我感到困惑,因为如果“this”指向它自己的对象,那么强制转换它(没有继承)如何允许我访问其他类成员? I think I'm just overall confused on what exactly casting "this" is doing for the compiler, considering its address doesn't change.
考虑到它的地址不会改变,我想我只是对“this”到底为编译器做了什么而感到困惑。
template<class T>
class A
{
public:
void call_fn()
{
reinterpret_cast<T*>(this)->fn();
}
};
class B
{
public:
void fn()
{
std::cout << "B function called" << std::endl;
}
};
int main()
{
A<B> obj;
obj.call_fn(); //prints out "B function called"
}
A non-static method call is just like a plain function call but with a hidden this
parameter pointing at the object.非静态方法调用就像一个普通的函数调用,但有一个隐藏的
this
参数指向对象。 The code shown is roughly equivalent to the following:显示的代码大致相当于以下代码:
class A {};
class B {};
void B_fn(B* this);
void A_call_fn(A* this) {
B_fn(reinterpret_cast<B*>(this));
};
void B_fn(B* this) {
std::cout << "B function called" << std::endl;
}
int main() {
A obj;
A_call_fn(&obj);
}
A::call_fn()
is type-casting its A* this
parameter to B*
, and then calling B::fn()
with that casted pointer as its B* this
parameter value. A::call_fn()
正在将其A* this
参数类型转换为B*
,然后使用A* this
强制转换的指针作为其B* this
参数值调用B::fn()
。 A reinterpret_cast
is effectively a brute-force cast, it really goes out of its way to try to oblige your request. reinterpret_cast
实际上是一种蛮力转换,它确实竭尽全力满足您的要求。 So you are telling the compiler that you know what you are doing and just accept it.所以你告诉编译器你知道你在做什么并且接受它。 So it does.
确实如此。 But you are invoking undefined behavior , because like you said,
A
and B
are unrelated types.但是您正在调用undefined behavior ,因为就像您说的那样,
A
和B
是不相关的类型。
The code happens to work, but only because B::fn()
makes no use of its B* this
parameter, so it doesn't matter whether this
is actually pointing at a valid B
object or not.该代码恰好工作,但只是因为
B::fn()
是没有使用其B* this
参数,所以也没有也罢, this
实际上是指向一个有效B
对象与否。 The code is ultimately no different than if you had done this instead:代码最终与您这样做时没有什么不同:
int main() {
std::cout << "B function called" << std::endl;
}
But, if you were to change B
to hold a non-static data member that B::fn()
actually uses, then the code will fail more noticeably.但是,如果您要更改
B
以保存B::fn()
实际使用的非静态数据成员,那么代码将更加明显地失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.