I want to ask you what are the best practices to dynamically create and manage objects in a real time environment. Basically, I need to create a bunch of objects on the fly. If the objects meet the criteria, they will be played and then destroyed after a while. So far I’m trying with an OwnedArray, but it doesn’t seem to retain the objects at the required index.
What I currently do is, basically, this:
for(int i = 0; i < maxItems; ++i)
if(shouldBePlayed[i] == true)
if(myObj* obj = objArray[i])
output += obj->play();
shouldBePlayed[i] = false;
if(shouleBePlayed[i] == false)
myObj* obj = new myObj();
shouldBePlayed[i] = true;
The main issue is that the objects are created but almost never destroyed because I get a nullptr at objArray[i]. That’s why I think OwnedArray might not be the perfect way to handle that.
When you remove an object from the OwnedArray using the remove() method, the subsequent objects get moved back to close the gap so you will lose the indexing of your elements. OwnedArrays are capable of holding null pointers so if you want to retain the indexing then you can set the object that you want to destroy to nullptr instead of removing it.
Also, make sure you are not doing this on the audio thread (this looks a lot like audio code) as creating and destroying objects on the audio thread is a very bad idea and can lead to errors/glitching in audio output.
A lockfree queue would be the best fit for this. There is one from moodycamel that is pretty mature.
Thanks guys. I ended up filling the OwnedArray with all the needed objects and then just activating the one I need in the loop. I totally forgot to loop backwards (for i = maxItems; --i >=0) for those kind of arrays. Now it works as expected.
Thanks a lot!