Firstly, I am getting confused about the best way to handle storing component objects:
The audio plugin demo uses normal “pass-by-value” for components (this seems more natural to me). There is nothing to worry about in the destructor.[/]
The Juce Demo uses pointers to store components, and uses deleteAndZero in the destructor (which the wiki strongly discourages)[/][/list]
Which (if either) of these methods is preferable, are there certain advantages / disadvatages to each? For example I sometimes find myself storing sets of repetitive components in arrays. Does either method lean itself to this more?
Secondly, I am in the situation where I have a number of large Sample objects (my own class which contains, amongst other things, an AudioSampleBuffer of data) which I want to store as a pool using an Array object. Currently, as I don’t want to be making copies of the data, I’m doing:
I’m sure it was drilled into me that when you use “new” there should always be a corresponding “delete”. Should I be worried about this and if so, how do I get around this? Also if I want to go about clearing the both array and the data / memory in it, which is the best way to go about this?
See how the delete disapeared ? That’s what Jules means in his code comments when he says "always use RAII"
This is a better approach because
you obviously don’t have to delete manually
it’s working even when the code follows a non-trivial path (think exceptions for example)
It’s also a good practice to use “JUCE_LEAK_DETECTOR()” on all your classes, so you know at shutdown, if you leaked anything.
[quote]I’m sure it was drilled into me that when you use “new” there should always be a corresponding “delete”. Should I be worried about this and if so, how do I get around this? Also if I want to go about clearing the both array and the data / memory in it, which is the best way to go about this?
This is a matter of pointer ownership (look it up, you’ll find plenty of usefull information)
The one who deletes is the one who owns.
Array doesn’t owns the objects, so if you “new” something into an array, you will have to delete it.
If you use OwnedArray for example, your array will own the objects, so you don’t need a delete matching your new. If you put an object into an OwnedArray, it will be deleted when the array is destroyed
Thanks, lots of solid advice there. Interestingly, Visual Studio 2010 was marking the code below with the errors (despite compiling fine):
Error: a value of type “juce::Slider *” cannot be assigned to an entity of type “juce::ScopedPointerjuce::Slider *”. Error: argument of type “juce::ScopedPointerjuce::Slider *” is incompatible with parameter of type “juce::Component *”.
// gainSlider is type ScopedPointer<Slider>
gainSlider = new Slider("gain");
addAndMakeVisible(gainSlider = new Slider("gain"));
The solution (should others come across this) is just to rescan the solution, I think it just rebuilds the Intellisense database.