Newb - is it better to create a "reference" to the AudioBuffer or a "pointer" in Juce?

Actually I have three AudioBuffers, and I want to create a vector of “references” or “pointers”, and I wonder which one is wisest to go with.

So, in PluginProcessor.h I have this:

AudioBuffer<float> mMybuffer1;
AudioBuffer<float> mMybuffer2;
AudioBuffer<float> mMybuffer3;

Now I want to create a vector which holds the addresses of these three buffers. I could do it with pointers. PluginProcessor.h:
std::vector<AudioBuffer<float> *> my_vector_of_pointers = { &mMybuffer1, &mMybuffer2, &mMybuffer3 };

Or references (is this declaration correct?):
std::vector<AudioBuffer<float> &> my_vector_of_references = { &mMybuffer1, &mMybuffer2, &mMybuffer3 };

Which method would be wisest to use in the context of Juce?

Well, normally I’d use pointers. (Whether using JUCE or not, just standard C++.) I’ve never put references in a vector before. You can’t check their validity, or set them to NULL if the object they’re referring to goes out of scope. Just seems wrong to me.

And you have a syntax error in that second declaration. You’re taking the address of those buffers, which is not what a reference needs.

But why not just declare an array of AudioBuffer in the first place?

AudioBuffer<float> myBufferArray[3];
1 Like

I don’t think a vector of references will even compile for you. References are not normal data in C++, unlike a pointer. In general it’s not easy to hold them as members of other data structures, because you need to guarantee the referenced data will not go out of scope before the held reference.

So tl;dr, use a pointer. However, something smells weird here - why use a reference or pointer at all? Your plugin processor should own all the data it needs access to throughout its lifetime, so it shouldn’t be holding references or pointers to audio buffers that it doesn’t create (or if it does, they should be behind smart pointers).

2 Likes

@holy-city
What about a plugin that does need to create extra audio buffers, e.g. a delay-like plugin, or sample-chop plugin.
It needs to hold historic AudioBuffer data from a few bars/seconds ago, ( a few separate buffers needed).

Would it be OK to use the method suggested by Howard above I wonder:
AudioBuffer<float> myBufferArray[3];

If I use this I suppose there’s no need for a vector of smart pointers.
(I guess I should also research the difference between a pointer and smart pointer)…

You need something called a “circular buffer” to copy data from the incoming audio buffers into. Here’s a tutorial on creating a delay plugin in JUCE that may be helpful.

You don’t need multiple audio buffers, you just need one. But you can’t hold on to a pointer to an AudioBuffer that gets passed into processBlock, because the data it points to is only valid in that scope (it may be freed by the host afterwards).