Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > std::list of class pointers, understanding problem (with minimal example)

Thread Tools

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

Frank Steinmetzger
Posts: n/a
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 {
int i;
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);
output(list1); output(list2);

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

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

Gruß | Greetings | Qapla'
Mein Gewissen ist rein! denn ich habe es nie benutzt!

Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Portability Problem; Minimal Example C Programming 9 08-09-2010 11:57 AM
std::list of class pointers, understanding problem (with minimal example) Frank Steinmetzger C++ 4 07-29-2010 04:12 PM
problem understanding :: operator in bitset class declaration C++ 5 01-05-2008 09:02 AM
Nested Class, Member Class, Inner Class, Local Class, Anonymous Class E11 Java 1 10-12-2005 03:34 PM
ASPNET_WP.EXE Hangs (W2K/IIS5/ASP.NET 1.1) With Minimal Load Ken Barrett ASP .Net 5 11-16-2003 08:03 PM