C++推送前迭代

Mar*_*ari 0 c++ iteration for-loop

我有一个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);  
}
Run Code Online (Sandbox Code Playgroud)

现在为有问题的代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

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

offset.x = 25
offset.y = 30
Run Code Online (Sandbox Code Playgroud)

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

offset.x = 150
offset.y = 150
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

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

offset.x = 16272
offset.y = 17
Run Code Online (Sandbox Code Playgroud)

而第三只打印segmentation fault:(

Hug*_*rrá 6

请注意,您的方法getComponents()返回一个副本,您应该返回一个引用.

list<Component*>& Tab::getComponents() {
    return (this->components);
}
Run Code Online (Sandbox Code Playgroud)


tim*_*rau 5

你的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;
}
Run Code Online (Sandbox Code Playgroud)

it取消引用它时,迭代器无效.