#include <vector.h>
#include <iostream.h>
#include "test.h"
usingnamespace std;
int main ()
{
vector<Test*> myvector;
vector<Test*> secondTest;
myvector.push_back (new Test ("Hello World"));
myvector.push_back (new Test ("testing 1 2 3"));
myvector.push_back (new Test ("ok, enough!"));
Test t1 = Test ("Second Test");
Test t2 = Test ("Second Test 2");
Test t3 = Test ("Second Test 3");
secondTest.push_back (&t1);
secondTest.push_back (&t2);
secondTest.push_back (&t3);
for (vector<Test*>::iterator iter=myvector.begin ();
iter != myvector.end ();
iter++)
{
cout << "delete from myvector" << endl;
delete *iter;
}
for (vector<Test*>::iterator iter2=secondTest.begin ();
iter2 != secondTest.end ();
iter2++)
{
cout << "delete from secondTest" << endl;
delete *iter2;
}
return 0;
}
test.h
1 2 3 4 5 6 7 8 9
class Test
{
public:
Test (constchar* data);
~Test ();
private:
char* data_;
};
thanks firedraco, i figured that was part of my problem. is there a way to determine if they have or have not been new'd? i think that was my underlying concern because i have handle to vectors and lists (in my other application; not this contrived app) that have pointers to objects, but when i clean (via clean ()), i currently just call delete; thus the crash. how can i put in logic to determine if they should be deleted?
kbw, thanks for the feedback too. i understand it is an error (runtime), but the compiler lets me do it.
No, you can't tell. You have to just know. Alternatively, you can use a "smart pointer" which basically deletes itself when there are no more pointers to the data. See Boost's smart pointer and their pointer containers.
That's what classes are really for, to break up the program into little veritable chunks. The general idea is if you break up your program into classes, confirm that each class behaves properly and interacts with other classes properly, you'll have a properly behaved class.
In your example, it's easy to see (with some experience) that:
- myvector's content should deleted
- when the content was deleted, myvector should have been cleared
- secondTest content shouldn't be deleted
- if the parameter passed in to the Test's constructor is at least 32 bytes, it will overwrite data_ and corrupt the heap.
This is all possible because the program uses objects. When you fix these little errors, the whole program is improved.