Std::unique_ptr


#1

So I noticed in the Main.cpp that ScopedPointer mainWindow; changed to std::unique_ptr mainWindow; Coming from a C# I have been contented just using new and delete concept as this made sense to me (I have been bitten a few times with the sequencencing when destroying and access violations on threads). Reading the roadmap saying that juce library wants to replace out ScopedPointer in favour of the standard libraries unique_ptr is this the correct way of using in a juce context or is there going to be a different way?

public:
    std::unique_ptr<Header> header;

then used…

addAndMakeVisible( (header = std::make_unique()).get() );


#2

If this object has a default constructor, then why use a pointer at all? Unless you actually need it to be a pointer, just using a member variable is by far the best way of handling object lifetimes.

public:
    Header header;


addAndMakeVisible (header);

#3

Cheers, yeah I usually do that with controls such as knobs, sliders, buttons e.t.c. but I do find it handier to have things like scenes to be pointers as I have an extended component class with a few extra methods for passing info and events between. Just checking that I wasn’t doing anything stupid if I did it that way?


#4

Yeah, it’s fine.

I think it’d read better like this though:

header = std::make_unique<Header>();
addAndMakeVisible (*header);

#5

Or you may prefer to do it all on one line

addAndMakeVisible(*(header = std::make_unique<Header>()));,

which is how I ended up doing it when I refactored to remove all the ScopedPointers.


#6

It’s a common use-case. I wonder if it would make sense to add a templated method to Component like this?

template <typename ChildCompType, template... Parameters>
std::unique_ptr<ChildCompType> createChild (Parameters...);

…so you could write


struct ParentComp
{
    ParentComp()
    {
        child = createChild<MyChild> (1234);
    }

    std::unique_ptr<MyChild> child;

#7

I was about to propose adding that. :slight_smile: