JUCE Looping Audio Advanced Tutorial question re: ReferenceCountedObject

In this tutorial that shows thread-safe methods for looping audio, it says:

void checkForBuffersToFree()
{
    for (auto i = buffers.size(); --i >= 0;)                           // [1]
    {
        ReferenceCountedBuffer::Ptr buffer (buffers.getUnchecked (i)); // [2]
        if (buffer->getReferenceCount() == 2)                          // [3]
            buffers.remove (i);
    }
}
  • [1]: It is useful to remember to iterate over the array in reverse in these situations. It is easier to avoid corrupting the array index access if we remove items as we iterate over the array.
  • [2]: This retains a copy of a buffer at the specified index.
  • [3]: If the reference count at this point is equal to 2 then we know that the audio thread can’t be using the buffer and we can remove it from the array. One of these two references will be in the buffers and the other will be in the local buffer variable. The removed buffer will delete itself as the buffer variable goes out of scope (as this will be the last remaining reference).

Question:
At [3], why/how does a reference count of 2 indicate that the audio thread is not using the buffer? It seems that making a copy of any buffer here that already exists would make the reference count 2…

The buffers array is holding reference no. 1 and the Ptr buffer in [2] is reference no. 2.
So there can’t be any more reference anywhere else.
Note it’s taking the reference count of the item buffer created in [2], not from the whole array.

1 Like

Ah, thanks - so if the audio thread was using it, the reference count would be 3? That’s what I was missing… {lightbulb}

Yes, that’s the answer :slight_smile: