ReferenceCountedObject problems

Hello everybody!

I'm kind of new to C++ and Completely new to Juce. This is a little embaressing but i need a little help understanding the ReferenceCountedObjects. I have the following code:

void CyclerComponent::mouseDoubleClick(const juce::MouseEvent &e)

{

    ReferenceCountedObjectPtr<HandleComponent> hc = new HandleComponent();

    hc->setCentrePosition( e.getMouseDownX(), e.getMouseDownY() );

    addAndMakeVisible(hc);

}

So i would assume the ReferenceCountedObjectPtr should be incremented when passing it to addAndMakeVisible() and the Object not beeing deleted until the parent Component gets deleted. Am i wrong? The object sticks around if i increment the reference count manually but then i get leaks when closing the app..

Thank you for your help!

You've declared the ref ptr for HandleComponent on the stack, so once mouseDoubleClick is finished the reference count will be decremented.  addAndMakeVisible only deals with regular pointers so you shouldn't assume it will play along with the shared management of the HandleComponent.  You can also step through it with the debugger and watch the reference count so you don't have to assume.

That said, to keep your HandleComponent managed then you probably want to add a member to your CycleComponent class:

class CycleComponent {

...

ReferenceCountedObjectPtr<HandleComponent> handle; //if you only ever want one at a time

ReferenceCountedArray<HandleComponent> handles; //if you want to have many

...

}

Also, although it will work fine you don't necessarily need to use a ref counted ptr.  If the Handles created for a CycleComponent will only ever belong to that particular CycleComponent then you might want to consider using ScopedPointer or OwnedArray.  Ref counted pointers are convenient but you end up with less indication of who's responsible for that memory.