[C++] If statement still executes code even though condition is untrue

I’m working with Cellular Automata.
I have a vector of Automaton objects called Automata, each automaton contains a m_auto_time member, this is the automaton’s age, or how long it’s been active for, here’s the function that iterates over the vector every frame:

void Grid::updateAutoSerial() {

	for (int i = Automata.size() - 1; i >= 0; i--) {
		Automata[i].updateClock();
		if (Automata[i].m_step_time > Automata[i].m_step_duration) {
			Automata[i].countneighbors();
			Automata[i].applyRules();
			if (Automata[i].m_manage_chunks_flag) { Automata[i].manageChunks(); }
		}
		if (Automata[i].m_auto_time > Automata[i].m_auto_duration) { Automata.erase(Automata.begin() + i); } 
	}
	
}

The condition at the end is the one that matters, when m_auto_time is higher m_auto_duration, which is how long the automaton is supposed to be active for, the automaton is erased from the vector.

The problem is, if I push_back() one automaton into the vector and set it’s duration for 5 seconds for example, after 5 seconds it will be erased as expected, but if I push_back() another automaton, regardless of what duration I give it, it will be immediately erased because for some reason, the new automaton would be storing the age of the previous automaton, which was somehow still going up even though that vector element was erased AND the entire vector was empty, so I tried setting m_auto_time to 0, in it’s class declaration, the constructor, the destructor, and even manually in the main.cpp file, but even that didn’t matter, because even though the new automaton, which now inhabits the spot of the previous automaton, has it’s age at 0 at the moment of it’s creation, the condition still immediately erases it for some reason.
What am I doing wrong?

NOTE: I should mention, parameters like m_auto_duration are initialized through a function, not through the constructor, don’t know if that’s relevant or not.

Looks like pointers and memory allocation.
Long and difficult topic.
Watch this helpful video.

2 Likes

I’m familiar with pointers so I didn’t watch the video, but you mentioning pointers did remind me that vectors are infact pointers and deleting them doesn’t necessarily delete the data they were pointing to and I’d have de-allocate the memory the vector element is pointing to.

I currently moved on to other parts of my project but now I know how to fix this bug once I get back to it, I’ll just leave this for anyone who stumbles this thread in the future.

Thank you so much!

2 Likes