Siddharth Krishnamoorthy Siddharth Krishnamoorthy - 3 months ago 21
C++ Question

C++ list insertion strange behavior

I have a class called Particle, and another called ParticleList, which is essentially a List of Particles plus some other functions. I'm noticing some strange behavior when I try to insert a new particle into ParticleList and I'm wondering why that is happening. The classes are defined as:

class Particle {
public:
// Particle data members
int index;
vector<double> r_last;
vector<double> r;
vector<double> v;

double m;
double q;

Particle(int i, double m, double q, int ndim) :
index(i), m(m), q(q) {
r_last.resize(ndim,0);
r.resize(ndim,0);
v.resize(ndim,0);};

Particle() { };
Particle(const Particle& p);
}


and

class ParticleList : public list<Particle> {
public:
int highestIndex;
size_t numParticles;
ParticleList() {highestIndex = 0; numParticles=0;}


/*below are functions that call the List<Particle>::push_back()
and List<Particle>::push_front() functions and increment numParticles*/

void push_back(const Particle& p);
void push_front(const Particle& p);

//some more member functions here

};


Definition of push_back and push_front:

void ParticleList::push_back(const Particle &p) {
numParticles ++;
list<Particle>::push_back(p);
}

void ParticleList::push_front(const Particle &p) {
numParticles ++;
list<Particle>::push_front(p);
}


The trouble comes in when I try to insert a particle as follows:

ParticleList newParticleList;
Particle newParticle(1, 0.5, 0.5, 2);
/*creates a particle with index 1, mass and charge 0.5, and 2 dimensions.
Variables r, r_last and v are set to vectors {0,0}*/

for (int i=0;i<nDim;i++)
newParticle.r[i]=0.5 //just changed newParticle.r, everything else still {0,0}

newParticleList.push_back(newParticle);


For some reason, when I do the last step, the value of the r_last vector for the list member that just got inserted changes to the value of the r vector. So if I print out newParticle.r_last, that'd give me {0,0}, but if print out the member of the list:

auto ii=newParticleList.end();
ii--;
Particle p=*ii;
for(int i=0;i<p.size();i++)
cout<<p.r_last[i];


I get {0.5,0.5}, which is the value of p.r. If I change the r vector after this point, it doesn't affect the value of r_last...only when I push_back does it create this effect. I've tried different computers, removed optimization flags, tried push_front and insert, and it's still the same behavior. Does anyone have ideas on what might be causing this?

Thank you!

Siddharth

Answer

Here Particle p=*ii; you create a copy of Particle object. So check your copy constructor Particle(const Particle& p);. May be it incorrectly copies p.r into p.r_last.