std::list of class pointers, understanding problem (with minimal example)

Discussion in 'C++' started by Frank Steinmetzger, Jul 28, 2010.

  1. Hello group

    I am trying to solve a segfault in a project of mine. To better understand
    what’s going on, I wrote a minimal program to see how deletion of list
    elements behaves if the list stores only pointers to class instances.

    Looking at the STL source confirmed what I suspected - the instance is not
    deleted when erasing the list item and its pointer, so I did not find the
    solution to my primary problem yet.

    But I found something else in the program that I am curious about. It:
    - defines a class k with a private member and an accessor get()
    - uses std::list<k*> to store some instances of k
    - has an output function that iterates through a list and outputs the
    value of the class pointer and the result of pointer->get()
    - declares two lists and fills them with three identical class instances
    - deletes the middle item in list 1 and destroys its instance of k

    List 2 has now, to my understanding, an invalid pointer in item 2, so it
    should segfault when calling the output function, should it not?

    But instead, the output function prints out "0". Where am I wrong here?
    Thanks in advance for your time.


    Here’s the program:


    #include <iostream>
    #include <list>

    using namespace std;

    class k {
    private:
    int i;
    public:
    k(int _i) {i=_i;};
    int get() {return i;}
    ~k() {cout << "destroyed #" << i << endl;}
    };


    void output(list<k*> &l) {
    for (list<k*>::iterator i=l.begin(); i!=l.end(); i++)
    cout << (*i) << ": " << (*i)->get() << endl;
    cout << endl;
    }

    int main (int argc, char* argv[]) {
    list<k*> list1,list2;
    k* pk;
    for (int i=1; i<4; i++) {
    pk=new k(i);
    list1.push_back(pk);
    list2.push_back(pk);
    }
    output(list1); output(list2);

    list<k*>::iterator it=list1.begin();
    it++;
    delete(*it);
    list1.erase(it);

    output(list1); output(list2);
    return 0;
    }

    --
    Gruß | Greetings | Qapla'
    Mein Gewissen ist rein! denn ich habe es nie benutzt!
     
    Frank Steinmetzger, Jul 28, 2010
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. jimjim
    Replies:
    18
    Views:
    7,363
    Default User
    Apr 12, 2004
  2. Siegfried Heintze
    Replies:
    0
    Views:
    461
    Siegfried Heintze
    Nov 25, 2006
  3. Replies:
    6
    Views:
    652
    Jim Langston
    Oct 30, 2005
  4. Frank Steinmetzger
    Replies:
    4
    Views:
    1,653
    Frank Steinmetzger
    Jul 29, 2010
  5. Replies:
    9
    Views:
    284
Loading...

Share This Page