push_back(this)将错误的指针推送到向量上

时间:2009-08-06 22:53:10

标签: c++

我有一个存储在另一个对象中的UnderlyingClass指针的向量,并且在UnderlyingClass中的一个方法内部我想将“this”指针添加到该向量的末尾。当我在push_back调用之后立即查看向量的内容时,错误的指针就在那里。可能出现什么问题?

cout << "this: " << this << endl;
aTextBox.callbacks.push_back(this); 
cout << "size is " << aTextBox.callbacks.size() << endl;
cout << "size-1: " << aTextBox.callbacks[aTextBox.callbacks.size()-1] << endl;
cout << "back: " << aTextBox.callbacks.back() << endl;
cout << "0: " << aTextBox.callbacks[0] << endl;
cout << "this: " << this << endl;
cout << "text box ptr: " << &aTextBox << endl;
cout << "text box callbacks ptr: " << &(aTextBox.callbacks) << endl;

这是输出:

this: 0x11038f70
size is 1
size-1: 0x11038fa8
back: 0x11038fa8
0: 0x11038fa8
this: 0x11038f70
text box ptr: 0x11039070
text box callbacks ptr: 0x11039098

顺便说一句,回调是WebCallback指针的向量,而UnderlyingClass实现了WebCallback:

std::vector<WebCallback*> callbacks;


class UnderlyingClass
    :public WebCallback 

复制评论:(见下面的答案)

输出:

this: 0x6359f70 
size is 1 
size-1: 0x6359fa8 
back: 0x6359fa8 
0: 0x6359fa8 
this: 0x6359f70 
WebCallback This: 0x6359fa8 
text box ptr: 0x635a070 
text box callbacks ptr: 0x635a098 

好的,这就解释了为什么指针不匹配。

我真正的问题是:

如何获取要调用的方法的正确版本?具体来说,WebCallback规定实现onWebCommand()函数,现在回调[0] - &gt; onWebCommand()不会导致我在UnderlyingClass中编写的onWebCommand()被执行。

2 个答案:

答案 0 :(得分:8)

如果您的布局如下所示,则可能会发生多重继承:

class UnderlyingBase {
  char d[56];
};

class UnderlyingClass
    :public UnderlyingBase, 
     public WebCallback {

};

然后,对于每个涉及的对象,布局可以是这样的。最后一个是包含前两个作为基类子对象的完整对象,并且您获取指针,并将其转换为WebCallback*

[UnderlyingBase]
 > char[56]: 56 bytes, offset 0x0

[WebCallback]
 > unknown:  x bytes, offset 0x0

[UnderlyingClass]
 > [UnderlyingBase]: 56 bytes (0x38 hex), offset 0x0
 > [WebCallback]:    x  bytes, offset 0x38

现在,由于向量包含WebCallback*,编译器会将指针调整为指向WebCallback子对象,而指向UnderlyingClassUnderlyingBase时,它会提前开始0x38(56)字节。

答案 1 :(得分:3)

将此内容添加到您的打印输出中:

cout << "this: " << this << endl;
cout << "WebCallback This: " << dynamic_cast<WebCallback*>(this) << endl;

我打赌这就是你要找的东西。

相关问题