I am storing the address of an Object in more than one entry in a vector;
At the time of Deallocating the memory, I am retriving the Pointers one by one and Deleting it; The problem is that say &Obj is stored at indexes 1, 3;
delete works first time; But it fails at 3rd index since it has been deleted in the first iteration itself; Could any body help me out to solve this ;
Here is the Sample Code;

class A{//...};
typedef map<int, A*> Type_t;
Type_t MyMap;
A *p = new A();
MyMap[1] = p;
MyMap[2] = p;
MyMap[3] = p;
//...
A* dPtr;
for( Type_t::iterator iter = MyMap.begin(); iter != MyMap.end(); iter++)
{
dPtr = (*iter).second;
delete dptr; //Works fine for the first time, But fails from 2nd Iteration
}
-Narayan

I tried this also, but still i am facing the same problem.

MyMap[1] = p;
 MyMap[2] = p;
 MyMap[3] = p;

Why start at 1 when element 0 is the first element?

Take a look at this.Maybe It can give you some ideas.

#include <vector>
#include <iostream>
#include <algorithm>
#include <boost/shared_ptr.hpp>

struct Foo
{ 
  Foo( int _x ) : x(_x) {}
  ~Foo() { std::cout << "Destructing a Foo with x=" << x << "\n"; }
  int x;
  /* ... */
};

typedef boost::shared_ptr<Foo> FooPtr;

struct FooPtrOps
{
  bool operator()( const FooPtr & a, const FooPtr & b )
    { return a->x < b->x; }
  void operator()( const FooPtr & a )
    { std::cout << " " << a->x; }
};

int main()
{
  std::vector<FooPtr> foo_vector;

  foo_vector.push_back( FooPtr(new Foo(3)) );
  foo_vector.push_back( FooPtr(new Foo(2)) );
  foo_vector.push_back( FooPtr(new Foo(1)) );

  std::cout << "Original foo_vector:";
  std::for_each( foo_vector.begin(), foo_vector.end(), FooPtrOps() );
  std::cout << "\n";

  std::sort( foo_vector.begin(), foo_vector.end(), FooPtrOps() );

  std::cout << "Sorted foo_vector:";
  std::for_each( foo_vector.begin(), foo_vector.end(), FooPtrOps() );
  std::cout << "\n";
  return 0;
}

>could you help me in some questions
If you bother to ask them, and in a separate thread unless they are directly related to the original question asked in this thread or one of the replies.

This article has been dead for over six months. Start a new discussion instead.