Siddharth Krishnamoorthy Siddharth Krishnamoorthy - 1 year ago 64
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 {
// 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) {

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


class ParticleList : public list<Particle> {
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 ++;

void ParticleList::push_front(const Particle &p) {
numParticles ++;

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}


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();
Particle p=*ii;
for(int i=0;i<p.size();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!


Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download