Tutorial: Looping audio (advanced) thread question

I’m pretty new to JUCE and also just learning c++ so I apologize if this is a simple question or if it has been answered already. I searched and didn’t see it but it’s probably because it’s obvious to everyone but me.

So, I see that in this discussion of threading, it’s mentioned that you want to make sure that memory is neither allocated nor deleted on the audio thread. In the openButtonClicked() function this is called

ReferenceCountedBuffer::Ptr newBuffer = new ReferenceCountedBuffer (file.getFileName(),

and in getNextAudioBlock(…) the following is called

ReferenceCountedBuffer::Ptr retainedCurrentBuffer (currentBuffer)

Why does one need to use the new keyword and the other doesn’t?

I think it is because in the first call, which runs on the message thread, you’re actually initializing a new buffer from the audio file whereas in the second one you’re only creating a pointer to the pre-existing buffer, currentBuffer, is that correct?

Yes that’s correct. In the openButtonClicked() funtion it’s safe to allocate memory. In the getNextAudioBlock() you’re effectively just taking a copy of the pointer, but the ReferenceCountedBuffer::Ptr maintains a count of these pointer pointer values such that the delete operator is called when no more references are live.

Timur’s talk at CppCon2015 explains this process and the caveat of being careful not to allow the final reference count to drop to zero in the audio thread: https://www.youtube.com/watch?v=boPEO2auJj4

1 Like

Awesome! Thanks for the information. I just wanted to make sure I was
understanding correctly. I have to give that video another watch. I saw it
once before but there’s definitely a lot more for me to get out of it.