Reputation: 13
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?
Upvotes: 1
Views: 191
Reputation: 966
I think the exception is due to the fact that you are allocating the memory only once in "Bar* b = new Bar()" and you are deleting it twice.You should allocate twice and then your code will not throw an exception.
Upvotes: 0
Reputation: 477040
Solve it by not using the terrible idea of storing raw pointers in a container. Instead, use a container of smart pointers:
#include <memory>
#include <vector>
typedef std::shared_ptr<Foo> FooPtr;
std::vector<FooPtr> v;
FooPtr b(new Bar()); // #1
v.push_back(b);
v.push_back(b);
v.push_back(b);
// C++0x: even better method:
auto c = std::make_shared<Bar>(); // #2
v.push_back(c);
v.push_back(c);
v.push_back(std::make_shared<Bar>()); // #3
// Three distinct allocations of a Bar object have happened, #1, #2, and #3.
// No explicit deletions!
If you don't have C++0x, use the TR1 library:
#include <tr1/memory>
typedef std::tr1::shared_ptr<Foo> FooPtr;
(You don't have make_shared
in that case, because that's a new gimmick using rvalue references and forwarding.)
Upvotes: 2
Reputation: 146930
Use a shared_ptr
. You can find this in C++0x, TR1, or Boost. shared_ptr
knows how many pointers still point to an object and only delete it when it's the last one.
Upvotes: 3