I have a vector with some (among other classobjects) multiple added objects
class Foo {
...
vector<Bar*> v;
Bar* b = new Bar();
v.push_back(b);
v.push_back(b);
...
}
in Foo’s destructor I do
for (vector<Bar*>::iterator it = v.begin(); it != v.end(); ++it)
delete *it;
this causes an exception on the second iteration, because the object is already deallocated: “Access violation reading location 0xfeeefee2.”
How do I solve this problem?
Solve it by not using the terrible idea of storing raw pointers in a container. Instead, use a container of smart pointers:
If you don’t have C++0x, use the TR1 library:
(You don’t have
make_sharedin that case, because that’s a new gimmick using rvalue references and forwarding.)