Hey, I've got a bit of a problem:

vector<BaseClass*> stuffvector;
BaseClass* temp = new DerivedClass(par_a, par_b);
stuffvector.push_back(temp);
delete temp;

This causes the program to crash. I have virtual destructor, so the DerivedClass's destructor should be called just fine. Does it have something to do with the vector? 'Cause I don't really have anything else in mind that could cause the crash. :/

EDIT:
Actually, now that I've opened my eyes, the crash happens when I try to handle the objects contained in the vector.

Recommended Answers

All 2 Replies

> now that I've opened my eyes, the crash happens when I try to handle the objects contained in the vector.

If you open your eyes a wee bit more, you would also notice that after delete temp ; the vector contains (a copy of) a pointer which points to an object that does not exist any more - the object has been deleted.

This is what you want :

vector<BaseClass*> stuffvector;
BaseClass* temp = new DerivedClass(par_a, par_b);
stuffvector.push_back(temp);
stuffVector.pop_back(); //added, remove all accounts of 'temp'
delete temp;

But I lied, this is what you really wanted :

std::vector< boost::shared_ptr<BaseClass> > baseVec;
baseVec.push_back( new DerivedFromBase() );
//do stuff
baseVec.pop_back();
commented: shared_ptr: Wish more people automatically code with it +3
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.