I’m trying to create a CodeEditorComponent in a very simple way, just like a TextEditorComponent. But I find that it asserts, as the internal lines array inside CodeDocument is uninitialized. I can’t see anything in the documentation that gives me a solution. Can anybody help?
You have an ownership/lifetime problem here. This line in your initializer list:
editor(CodeDocument(), nullptr)
…creates a temporary CodeDocument object that the CodeEditorComponent takes by reference. As soon as that initialization happens, the CodeDocument you created goes out of scope and is destroyed, leaving the editor component pointing at an invalid object and boom.
See if this doesn’t put you in a better place:
{
public:
MainComponent() :
editor(doc, nullptr)
{
setBounds(0, 0, 100, 100);
setWantsKeyboardFocus(true);
addAndMakeVisible(editor);
}
void resized() override
{
editor.setBounds(getLocalBounds().reduced(10));
}
private:
CodeDocument doc; // document becomes a member of your component
CodeEditorComponent editor;
};
(or even better IMO is to have the CodeDocument owned someplace else in your app’s code as part of a model layer, and pass a reference to that into the component you’re building here, but that’s a design/philosophy issue)