指向基数的指针和指向派生对象的指针的内存布局的区别 [英] Difference in memory layout of pointer to base and pointer to derived object

查看:126
本文介绍了指向基数的指针和指向派生对象的指针的内存布局的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下课程:

class A
{
public:
  A(int val) : m_valA(val) {}

private:
   int m_valA;
};

class B : public A
{
public:
  B(int val) : A(0), m_valB(val) {}

private:
  int m_valB;
};


    B* pb = new B;

如果我有一个函数需要一个A *,例如:

if I have a function which takes a A*, eg:

void func(A* pVal) {}


$ b b

和pb传递给这个函数,那么就低级内存布局而言,pval(在函数中)和pb指针之间有什么区别?

and pb is passed to this function, then in terms of low level memory layout, what is the difference between pval (in the function) and the pb pointer?

不是指针指向对象的开始吗?

Doesn't a pointer point to the beginning of the object? In which case how will the two pointers be different?

推荐答案


指针不指向对象的开始?

Doesn't a pointer point to the beginning of the object? In which case how will the two pointers be different?

如果你传递一个指针到 B 对象 func(A * pVal),然后在 func() c $ c> pVal 指针将指向 B A >对象。它是未指定是否他们将在相同的位置(虽然对于一个简单的继承情况,在你的例子,它几乎肯定会是)。

If you pass a pointer to a B object to func(A* pVal), then inside the func() implementation the pVal pointer will point to the A sub-object part of the B object. It's unspecified whether they will be at the same location (though for a simple inheritance situation as in your example, it almost certainly will be).

如果 A 子对象实际上处于不同的偏移量(例如,如果涉及多重继承,则可能需要这样),则编译器将在编译时自动进行适当的调整呼叫。编译器可以这样做,因为在调用站点它知道它正在处理一个 B * ,并需要将其转换为 A * 传递到 func()。这是一个安全且正常的转换,因为 B 公开继承自 A

If the A sub-object is actually at a different offset (which might need to be the case if multiple inheritance is involved, for example), then the compiler will make the appropriate adjustment automatically when it compiles the call. The compiler can do this because at the call site it knows it's dealing with a B* and needs to convert it to an A* to pass to func(). That's a safe and normal conversion since B publicly inherits from A.

这篇关于指向基数的指针和指向派生对象的指针的内存布局的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆