bonkmaykr
@bonkmaykr@canithesis.org
40 following 24 followers
" and all objects are created with the new keyword, something like;
simulation->w_content.push_back(new o_bulletGeneric());
@bonkmaykr What is the vector's template parameter? If it's std::vector<o_worldObjectGeneric>
it'll still allow you to push derived objects, but it'll copy construct an o_worldObjectGeneric
instead of pushing the entire derived object on the vector. Look at this; notice how despite calling push_back
with four different objects, only "A copy construct" will be printed between "Before push_back" and "After push_back."
The vector stores o_worldObjectGeneric*, with the asterisk. So there should be no slicing.
@bonkmaykr My next hunch would be if you're doing any kind of multithreading or maybe accidentally using static_cast
instead of dynamic_cast
.
I managed to figure it out, IDK the low-level specifics but basically since updating world objects happens in the middle of a for() that reads the vector, it would see the new object get added to the end of the vector and try to call it's updateMe() while the vector was getting shifted around. Adding a lag of one game tick before each new object spawns by giving them a queue to wait in helped work around the issue. So I just do this before each tick:
for (globals::objects::o_worldObjectGeneric* o : w_contentQueue) w_content.push_back(o); w_contentQueue.clear();
@bonkmaykr You should generally avoid adding to a vector while iterating over it, especially if you're using the for(auto x : y)
syntax. What can happen is that when you try to push onto the vector and there's no more space, the vector allocates a new buffer and moves all the objects into it. This doesn't change the for loop iterators, so your for loop continues to loop over the destructed and freed objects.