Why all the ScopedPointers?


This question is perhaps showing my JUCE naievete, but I'm wondering why ScopedPointers seem to be used so extensively in code using JUCE?

Specifically, it seems most of the classes (such as UI components) could be data members instead of separately allocated. For example, I'm creating a dialog with the Introjucer and it generates a lot of scoped pointers and calling new ImageButton, etc. when it would seem those ImageButtons could just be data members, since their lifetime would be effectively the same.

Am I missing something? Just trying to better understand JUCE :)


I'm absolutely NOT a C++ aficionado, but, as I see it, they help remove the likelyhood of dngling pointers. Helps find coding/logic faults and thus results in better code.


I suppose ScopedPointer has the advantage of being able to transer ownership via its release method. But other than that, it has the same properties with respect to dangling pointers as a value would.

BTW, I'm not talking about manually allocating components via new/delete (clearly, ScopedPointer is better than that). I'm talking about having sub-componets be values (not pointers).


I wondered that myself. I don't use the IntroJucer and I just use them on the "stack". I guess since the IntroJucer gives you no choice, it can be useful in case you need to change when they're destroyed. I used to use the IntroJucer to lay things out, then I'd go and erase and change all the unnecessary code. I find it easier to just do it all in code now though. 


Have you read this yet? 




It's done like that for a few reasons - mainly for simplicity and uniformity, because although some types could be created as member variables, others can't (e.g. a custom class may have complex constructor arguments that aren't available until some other bit of code has been run). So rather than complicate things by making this an option, it was much easier just to put them all on the heap.

Also it means that if you need to tweak your code to delete one of these objects early, or to replace it with a new one, or to make sure they get deleted in the correct order, etc etc, then you can easily do so.