GetDunne Wiki

Notes from the desk of Shane Dunne, software development consultant

User Tools

Site Tools


avoid_new_delete_prefer_references_to_pointers_use_member_variables_for_sub-components

This is an old revision of the document!


Avoid new/delete, prefer references to pointers, use member variables for sub-Components

The JUCE library includes a nice collection of managed pointer template classes, such as juce::ScopedPointer, which can and should be used to avoid most uses of the delete keyword. Note that managed pointers are still assigned using new.

I checked my code carefully, and was unable to find any uses of delete, and found none. I did find a number of uses of new, however, which fell into two categories:

  1. In my VanillaJuceAudioProcessor class, I used new to create object-instances where there was effectively no choice; the JUCE library itself required it. I also used new when when creating juce::XmlElement objects, following the example of the JUCE static function juce::AudioProcessor::getXmlFromBinary(), which returns a non-managed pointer.
  2. In all of my GUI-related classes, I used new to create various juce::Component objects, assigning the result to juce::ScopedPointer member variables of the Gui… class. I used the Projucer to generate this code, and that's what it produced, so I assumed this was the recommended approach. I have since learned, through discussion on the JUCE Forum, that this is definitely not the case.
  1. In my VanillaJuceAudioProcessor class, I use new to create instances of SynthVoice and SynthSound, which are immediately added to the Synth object using juce::Synthesiser::addVoice() and juce::Synthesiser::addSound(), for both of which the JUCE documentation states that the juce::Synthesiser object will take care of deleting the passed-in object when required. As far as I could tell, there is no other way to add voices/sounds to a juce::Synthesiser other than by passing in a pointer, so these uses of new are unavoidable.
  2. Also in my VanillaJuceAudioProcessor class, in places where I used JUCE's built-in

so I have to assume that Jules's admonition to “ditch all your new/delete…” was something of a generic complaint.

avoid_new_delete_prefer_references_to_pointers_use_member_variables_for_sub-components.1504289213.txt.gz · Last modified: 2017/09/01 18:06 by shane