开发者

How to delete multiple added pointer of a vector?

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 (v开发者_Python百科ector<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?


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜