My grasp of pointers is quite weak, and I’m hoping someone more knowledgeable can tell me if I am using OwnedArray in a safe way.
What I’m doing is adding components (in this case Label) to an OwnedArray to make it easy to iterate over them later on. So I create each Label, add it to an OwnedArray, and do some setup on it. Here’s a stripped down example:
OwnedArray<Label> myOwnedArray; Label* myLabel = new Label("label-name", "Some Text"); myOwnedArray.add(myLabel); // Do some setup on myLabel, e.g. addAndMakeVisible(myLabel);
I’ve been reading about how raw pointers and “new” should be avoided in favour of smart pointers, and it’s made me worried that my approach is not ideal. I think my approach is safe, since OwnedArray takes ownership of the raw
Nevertheless I have also tried a different approach, passing a smart pointer to the OwnedArray’s add method:
OwnedArray<Label> myOwnedArray; auto myLabel = myOwnedArray.add(std::make_unique<Label>("label-name", "Some Text")); // Do some setup on myLabel, e.g. addAndMakeVisible(myLabel);
Is one approach preferable to the other? Or is there a better approach altogether?