Do new AudioBuffers really need to be clear()ed? (Answer: Yes!)

We have a bunch of code in our API like this:

// SomeClass.h
class SomeClass {
    std::shared_ptr<juce::AudioSampleBuffer> buf;
public:
    SomeClass(int channels, int samples);
}

// SomeClass.cpp
SomeClass::SomeClass(int channels, int samples)
    : buf(std::make_shared<juce::AudioSampleBuffer>(channels, samples))
{
    // zero (fill with silence) the audio buffer
    buf->clear();
}

(Yes, we’re really still using AudioSampleBuffer, which I know is just an alias for AudioBuffer<float>. It’s old code. But built with JUCE 5.4.7, so at least the APIs available are modern.)

My question, though: Especially in light of this other forum discussion regarding clear() and the fact that it doesn’t (necessarily) even clear the buffer at all, I’m wondering whether there’s any point to that initial buf->clear() in the constructor. Are newly-allocated buffers not initialized in a clear state, as our code’s comment would seem to imply? Or is it entirely superfluous code?

(I’m looking to validate my own inclination to rip out the clear(), I guess is the real motivation here. :angel: Unless of course it really is necessary, in which case I’d like to know that before I rip it out and break stuff.)

Looking into the sources, the bool flag isClear is initialised false, so it seems your clear() call should be kept.
But there is an argument in setSize() you can use in your prepareToPlay, which clears the buffer.

1 Like

@daniel Asked and answered! And in fact, now I see that the documentation is pretty clear on this point:

AudioBuffer()

template<typename Type>

AudioBuffer<Type >::AudioBuffer (
  int               numChannelsToUse ,
  int               numSamples
)

Creates a buffer with a specified number of channels and samples.

The contents of the buffer will initially be undefined, so use clear() to set all the samples to zero.

So, yes, I really should’ve just R’dTFM.