Shared_ptr for MainComponent?

I have an issue trying to pass my MainComponent around as a shared_ptr.
MainComponent inherits from std::enable_shared_from_this
MainWindow creates the MainComponent in a shared_ptr so that it is managed by at least one shared_ptr (as is required by enable_shared_from_this)
But calling shared_from_this() still generates a bad_weak_ptr error.

Is there something in the setContent… method that would copy the underlying object or break this approach in any other way?

class MainWindow    : public DocumentWindow
    {
    public:
        MainWindow (String name)  : DocumentWindow (name,
                                                    Desktop::getInstance().getDefaultLookAndFeel()
                                                    .findColour (ResizableWindow::backgroundColourId),
                                                    DocumentWindow::allButtons)
        {
            //setContentOwned (new MainComponent(), true);
            mnCmp =  std::make_shared<MainComponent>();
            setContentNonOwned(mnCmp.get(), true);

            setVisible (true);
        }
    public:
        std::shared_ptr<MainComponent> mnCmp;

    private:
        JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainWindow)
    };

You should first explain WHY you’re trying to share it before figuring out HOW to do it. The majority of the time, you should never share ownership of objects.

It defeats the purpose, since the setContentNonOwned will obviously save a raw pointer to your component, making it by no means safer to use a shared_ptr.

While shared_ptr is a nice approach, it has it’s use cases, where you cannot determine a definite ownership. Here the question of ownership is very clear, so it is not advisable to use shared_ptr.

I don’t know, if there is a safeguard in place to disallow a raw pointer to be kept. But it is bad practice anyway.

setContentNonOwned claims that it won’t delete the object pointed-to.
It also claims that it doesn’t mind if the object becomes deleted at some point in the future.
So it seemed reasonable to use shared_ptr as it adds some safety to the rest of the application when accessing the MainComponent object via weak_ptrs.

That is correct, the content is set to a safe pointer, so it is not dangerous, but having a dedicated ownership is preferred over a floating ownership between shared_ptrs.

Just consider, what sense the ResizeableWindow makes, when the main content component goes out of scope…

If your reason for shared_ptr is to have a easy and safe way to spread uncontrolled references, just remember, if two structures reference each other, the object goes never out of scope… I don’t think it is a wise choice, but that is now only my opinion.

The component class already has a built-in mechanism for that - you can use Component::SafePointers which are basically weak references