0

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.

Edited by bleedi: n/a

3
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by firstPerson
0

> 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.

1

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();
Votes + Comments
shared_ptr: Wish more people automatically code with it
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.