多重继承和 this 指针
假设我有这个结构:
struct vector_data
{
double x, y;
double& operator[](size_t index)
{
return * (static_cast<double*>(static_cast<void*>(this)) + index);
}
};
operator[] 应该按预期工作,因为 vector_data 是 POD 类型。 预期行为是 vector_data[0] 返回 x,而 vector_data[1] 返回 y。
现在假设我有第二个结构:
struct more_data
{
double evil_data;
// There could be more here, data or functions
};
并像这样从两者派生:
struct composed : public more_data, public vector_data
{
};
这会破坏运算符[]的预期行为吗?换句话说,派生结构中的 vector_data 的 this 指针是否仍指向该结构的 vector_data 部分,还是指向派生结构的开头?
如果它确实破坏了operator[],那么我该如何解决这个问题?我可以首先从vector_data继承,但假设compose包含虚函数。我知道大多数编译器将 vtable 放在最后,但这并不能保证。最好的方法是什么?
Suppose I have this struct:
struct vector_data
{
double x, y;
double& operator[](size_t index)
{
return * (static_cast<double*>(static_cast<void*>(this)) + index);
}
};
The operator[] should work as expected, because vector_data is a POD type.
The expected behaviour is that vector_data[0] returns x, and vector_data[1] returns y.
Now suppose I have a second struct:
struct more_data
{
double evil_data;
// There could be more here, data or functions
};
And derive from both like this:
struct composed : public more_data, public vector_data
{
};
Will this destory the expected behaviour of operator[]? In other words, will the this-pointer of vector_data in the derived struct still point to the vector_data part of the struct, or will it point to the beginning of the derived struct?
If it does destroy operator[], then how can I resolve this problem? I can inherit from vector_data first, but suppose composed contains virtual functions. I know most compilers put the vtable at the end, but this is not guaranteed. What would be the best approach?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
撇开不正确的指针算术问题不谈(
x
和y
之间填充的可能性使您的假设无效),这里是发生情况的快速说明使用多重继承时的 this
指针:showA
和showB
打印不同的数字;showC
打印与showA
相同的数字,因为a
在碱基列表中首先列出。如果您在那里切换a
和b
,那么showC
和showB
将是相同的。 “魔力”在于 C++ 编译器:它足够聪明,可以为每个成员函数提供正确的this
指针。Leaving aside the issues of your incorrect pointer arithmetics (the possibility of padding between
x
andy
invalidates your assumption), here is a quick illustration of what's going on withthis
pointer when you use multiple inheritance:showA
andshowB
print different numbers;showC
prints the same number asshowA
, becausea
is listed first in the list of bases. If you switcha
andb
there, thenshowC
andshowB
would be the same. The "magic" is in the C++ compiler: it is smart enough to give each member function a correctthis
pointer.也许你想要的是这样的:
Probably what you want is something like: