Use of ScopedPointer in synthesiser demo (noob question)


I am trying to learn a little about Juce, but I am no expert in programming. I do not understand exactly the use of the ScopedPointer below:

(that is from AudioSynthesiserDemo)

 void setUsingSampledSound()
        WavAudioFormat wavFormat;
        ScopedPointer<AudioFormatReader> audioReader (wavFormat.createReaderFor (new MemoryInputStream (BinaryData::cello_wav,                                                                                          BinaryData::cello_wavSize,
        BigInteger allNotes;
        allNotes.setRange (0, 128, true);
        synth.addSound (new SamplerSound ("demo sound",
                                          74,   // root midi note
                                          0.1,  // attack time
                                          0.1,  // release time
                                          10.0  // maximum sample length

Is it absolutely necessary ? Does it have to do with the dynamic allocation of MemoryInputStream ? Does it have to do with its use in SamplerSound constructor ?

Thank you in advance for your explanation

Have a read about the C++ operators new and delete: .

Also, feel free to read up on scope:

In short, a ScopedPointer, when it goes out of scope, simply handles deleting the object it has ownership over. This makes use of the RAII idiom to avoid accidentally leaking memory (i.e.: Forgetting to "delete" a heap object).

I suggest reading the description of the class for more information:

It's not necessary to use this, but it is suggested to use this approach since it's modern practice in C++. JUCE provides ScopedPointer because not all platforms implement the new C++11 stuff. Check out: and .

This type of thing has no direct relation to any class, it's a memory handling technique.

Thank you for your answer. I know it has to do mainly with C++ functionning rather than Juce. But I was wondering if the context here made it necessary.

In the following code, in AudioPlaybackDemo, there is a simple pointer:

        transportSource.setSource (nullptr);
        currentAudioFileSource = nullptr;
        AudioFormatReader* reader = formatManager.createReaderFor (audioFile);
        if (reader != nullptr)
  1. In the first case it is a classic RAII approach to manage the release of the object returned.

  2. In the second case the ownership of the object is passed to another object later in the code.

currentAudioFileSource = new AudioFormatReaderSource (reader, true);

And so a ScopedPointer would result in deleted the object twice.

Oh, I see. Thank you for your answer.

As jules collects black belts in RAII there MUST be a valuable reason somewhere to let a lonely pointer :wink: