J
joevandyk
Below, I have a class Container that contains a vector. The vector
contains pointers to a Base class. When the Container destructor is
called, I would like to delete all the objects that the pointers in the
vector are pointing to.
It works fine, IF I comment out the destructors in Base and Inherited.
If I leave the explicit destructors in there, it seg faults. Why is
there a difference?
Thanks,
Joe
#include <iostream>
#include <vector>
using namespace std;
struct Base {
virtual ~Base() {}
};
struct Inherited : public Base {
~Inherited() {}
};
class Container
{
public:
vector<Base*> v;
~Container()
{
// Need to delete pointed-to objects in v
for (vector<Base*>::iterator i = v.begin();
i != v.end();
++i)
{
cout << "Deleting " << *i << endl;
delete *i;
}
}
};
int main()
{
Container c;
Inherited *f = new Inherited();
// Adding two pointers to the same object to Container
c.v.push_back(f);
c.v.push_back(f);
return 0;
}
contains pointers to a Base class. When the Container destructor is
called, I would like to delete all the objects that the pointers in the
vector are pointing to.
It works fine, IF I comment out the destructors in Base and Inherited.
If I leave the explicit destructors in there, it seg faults. Why is
there a difference?
Thanks,
Joe
#include <iostream>
#include <vector>
using namespace std;
struct Base {
virtual ~Base() {}
};
struct Inherited : public Base {
~Inherited() {}
};
class Container
{
public:
vector<Base*> v;
~Container()
{
// Need to delete pointed-to objects in v
for (vector<Base*>::iterator i = v.begin();
i != v.end();
++i)
{
cout << "Deleting " << *i << endl;
delete *i;
}
}
};
int main()
{
Container c;
Inherited *f = new Inherited();
// Adding two pointers to the same object to Container
c.v.push_back(f);
c.v.push_back(f);
return 0;
}