我有一个Tab类,其中包含组件列表。

list<Component*> Tab::getComponents() {
    return (this->components);
}

void Tab::addComponent(Component* comp){
    this->components.push_front(comp);
}

Tab::Tab() {
    // x = 25, y = 30
Button* one = new Button(25,30,300,100, "images/button.png");
this->addComponent(one);

Button* two = new Button(75,100,300,100, "images/button.png");
this->addComponent(two);

    // x = 150, y = 150
Button* three = new Button(150,150,300,100, "images/button.png");
this->addComponent(three);
}


现在查看有问题的代码:

list<Component*>::iterator it = activeTab->getComponents().begin();
for (it ; it != activeTab->getComponents().end(); it++) {
    offset.x = (*it)->getX();
    cout << "offset.x = " << offset.x << endl;
    offset.y = (*it)->getY();
    cout << "offset.y = " << offset.y << endl;
}


这是for循环的第一次迭代的输出:

offset.x = 25
offset.y = 30


但是,看到我使用了push_front(),它应该是:

offset.x = 150
offset.y = 150


我究竟做错了什么?

编辑:for循环的第二次迭代打印垃圾...

offset.x = 16272
offset.y = 17


第三只打印segmentation fault :(

最佳答案

您的Tab::getComponents()返回list<Component*>而不是list<Component*>&,这意味着在返回时将复制this->components。因此,让我们看一下代码:

list<Component*>::iterator it = activeTab->getComponents().begin();
// ``it'' is already INVALID here since the list returned in the above line
// is already destructed!
for (it ; it != activeTab->getComponents().end(); it++) {
    offset.x = (*it)->getX(); //``it'' is invalid
    cout << "offset.x = " << offset.x << endl;
    offset.y = (*it)->getY();
    cout << "offset.y = " << offset.y << endl;
}


取消引用迭代器it时无效。

09-30 15:00
查看更多