Components on the heap


#1

Is it good practise to create component objects on the heap instead of the stack?

If so: Why?

 

In the WidgetsDemo.cpp of the JuceDemo application, all the component objects I encountered are created on the heap. The same happen to all the component objects created by the GUI Editor of the Introjucer.

Does the advice from http://www.juce.com/documentation/coding-standards

If a local variable can be allocated on the stack rather than the heap, then always do so.

only hold for variables and not for (Component) objects?


#2

The only time it'd be possible to use a local stack variable for a component would be if you create one and then run a modal loop - but modal loops are Very Bad, so you shouldn't be doing that kind of thing.


#3

Guess I haven't expressed myself very well.

What is the advantage of

class MainComponent : public Component
{

public:

    MainComponent
    {
        textButton = new TextButton ("push me");
        addAndMakeVisible (textButton);
    }

    resized()
    {
        textButton->setBounds (0, 0, 80, 30);
    }

private:

    ScopedPointer<TextButton> textButton;
};

compared to

class MainComponent : public Component
{

public:

    MainComponent
      : textButton ("push me")
    {
        addAndMakeVisible (&textButton);
    }

    resized()
    {
        textButton.setBounds (0, 0, 80, 30);
    }

private:

    TextButton textButton;
};

 

?


#4

That's not on the stack, it's a member variable.

But yes: if it's possible to use an in-place member rather than a ScopedPointer, you should do so. Mainly because it makes your syntax cleaner, but it's marginally faster + more compact too.


#5

Thank you Jules for this insight!

Sorry for my wrong posed question.