vector push_back deletes objects
Whenever I add an object to a vector, the destructors of all the
previous objects in the vector get called. Why? It seems a push_back
would just copy the object to add to the next free slot in the vector,
and leave all the other objects alone. The only time I could see this
is if the vector needs to add more memory, but this shouldn't happen
with every push_back call.
Test app:
#include <iostream>
using namespace std;
struct Location
{
Location();
Location(int a, int b);
~Location();
void show();
int x;
int y;
};
Location::Location()
{
x = 0 ;
y = 0 ;
}
Location::Location(int a, int b)
{
x = a ;
y = b ;
}
Location::~Location()
{
cout << "*** Location " << x << " , " << y
<< " destructor called *** " << endl << endl ;
}
void Location::show()
{
cout << "( " << x << " , " << y << " ) " ;
}
#include <iostream>
#include <vector>
using namespace std ;
int main()
{
vector<Location> Vec; // to store route
Location L[5] ; // Location array
// add co-ords to Location array
for ( int i = 0 ; i < 5 ; ++ i )
{
L[i].x = i ;
L[i].y = i ;
}
cout << endl << "Pushing .. " << endl ;
for ( unsigned int i = 0 ; i < 5 ; ++ i )
{
cout << endl << "Pushing .. " ;
L[i].show() ;
cout << endl ;
cout << "Vec push back start " << endl ;
Vec.push_back( L[i] ) ;
cout << "Vec push back end " << endl ;
}
cout << endl << "Leaving prog .. " << endl << endl ;
}