Frage

I was taught always to use a pointer list when storing objects, but I started using lists with objects in them instead. So I'm wondering how do I properly remove an object from a list?

The first code example removes from a pointer list and works all right, but the second one gives an error when running. Do I need to use delete when working with list with objects?

using namespace std;

struct SomeObject{
    SomeObject(int i){
        something=i;
    }
    int something;
};

void main(){



    list<SomeObject*> pointerList;
    SomeObject * op = new SomeObject(2);
    pointerList.push_back(op);

    auto pit = pointerList.begin();
    pointerList.erase(pit);
    delete *pit;

    cout<<(**pit).something<<endl;



    list<SomeObject> objectList;
    SomeObject o(1);
    objectList.push_back(o);

    auto oit = objectList.begin();
    objectList.erase(oit);
    delete &oit;//this one

    cout<<oit->something<<endl;



    int i;
    cin >> i;

}

Also what are down and upsides with doing it this way?

War es hilfreich?

Lösung

You get the error because oit is an iterator, not a pointer. You use delete on pointers acquired with new. Iterators look like pointers, but they are not pointers. In the example you gave it's just wrong to use delete.

I think it would be more idiomatic (and correct!) this way:

list<SomeObject*> pointerList;
SomeObject * op = new SomeObject(2);
pointerList.push_back(op);

auto pit = pointerList.front();
pointerList.pop_front();
// delete *pit; // wrong

cout << (**pit).something << endl;

list<SomeObject> objectList;
SomeObject o(1);
objectList.push_back(o);

auto oit = objectList.front();
objectList.pop_front();
// delete &oit; // wrong

cout << oit->something << endl;
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top