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.

Regarding the first category, I can only assume that Jules's admonition to “ditch all your new/delete…” was something of a generic complaint. Regarding the GUI-related classes, I now understand that the Projucer's lavish use of ScopedPointer is not at all recommended, and that child Component objects should be

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