SharedResourcePointer<>*

If I create multiple Component classes with private member…

SharedResourcePointer<SharedObjectType>* sharedResource;

and assign an address to the pointer in each Component’s constructor…

sharedResource = new SharedResourcePointer<SharedObjectType>;

…will I actually be creating a single shared resource, or a big mess?

If the answer is “a big mess”, is it possible to create a SharedResourcePointer member in such a way that doesn’t require the SharedObjectType to be #included in the .h file for the SharedResourcePointer’s parent class (i.e. to include the SharedObjectType in the .cpp instead)? If so, how?

I’m (still) trying to figure out a way to resolve this circular dependancy problem in order to continue using the Projucer’s GUI tweaking facilities in conjunction with a global LookAndFeel.

Many thanks in advance!

Hey willrice!

This is a bit odd, but as far as I can tell it shouldn’t create a big mess.

You would normally use the SharedResourcePointer directly on the stack:

class A
{
private:
     SharedResourcePointer<B> bPtr;
};

so without the extra pointer indirection. But if you really don’t want to include the header of B, I guess you could do what you are doing.

Just be sure to delete your sharedResource member variable (the one you are using in your code above). You need to match all your new calls with delete, because otherwise the reference count inside the SharedResourcePointer won’t go down unless you delete an instance every time you create one.

For this, I suppose you could use scoped pointers rather than raw pointers:

ScopedPointer<SharedResourcePointer<MyClass> > sharedResource;

A bit messy though.

2 Likes

Maybe the SharedResourcePointer is not the right type for what you’re doing. You could use a static std::unique_ptr or static juce::ScopedPointer. Interfaces are a good way to get rid of the circular dependency problem.

//MyClass.h:
#include "ISharedObjectType.h"

class MyClass
{
public:
...
private:
    static std::unique_ptr<ISharedObjectType> sharedResource;
};



//MyClass.cpp

#include "MyClass.h"
#include "SharedObjectType.h"

std::unique_ptr<ISharedObjectType> MyClass::sharedResource(new SharedObjectType);

No need do instantiate the shared resource in the constructor, unless that’s what you want to do. Don’t forget make the deconstructor in ISharedObjectType virtual, otherwise the decostructor of SharedObjectType will not be called and you might end up with memory leak.