SharedResourcePointer


#1

I've just added a new class SharedResourcePointer, which some of you may find handy.

Basically, it's a simple smart-pointer that automatically manages a shared static instance of an object. The interesting bit about it is that it's ref-counted, so that when all of your SharedResourcePointers go out of scope, the shared resource is also freed. That makes it a bit like a singleton, but more dynamic, and it means that your shared object will get deleted before shutdown without using DeletedAtShutdown, or relying on the runtime's statics being deleted.

In particular, this may be a good thing for plugins, where you don't really want to use a static or singleton, but have shared things, e.g. pre-calculated values or shared graphics, which you want to share between instances of your plugin.


#2

Nice addition! I think that most of us developing plug-ins already have wrapped their own solution for this kind of topic, it's good that it gets supported by the library now :)

One suggestion, though: as you did for some other such classes, I think that a small code example in the class documentation would greatly help understand what's the intended use for the class


#3

Yes, it's a pattern that I've found myself reinventing multiple times over the years without realising it. Will add a code example when I get a moment, and there are probably quite a few bits of existing code in the library which I'll be able to simplify with it.


#4

*cheers from the crowd*


#5

Very nice! 

And if someone can point me to programming solutions to share initialisation code and resources between plugin instances, I would be very grateful! 


#6

Can you show us an exapmle with a static variable?


#7

There's example code in the class's documentation.


#8

Isn't there a potential alignment issue with this code ? :

static SharedObjectHolder& getSharedObjectHolder() noexcept
    {
        static char holder [sizeof (SharedObjectHolder)] = { 0 };
        return *reinterpret_cast<SharedObjectHolder*> (holder);
    }

 

(since holder is not required to have the alignment needed by the SharedObjectHolder struct)


#9

Why would it matter whether or not it's aligned?

(Though TBH I'd be very surprised if any compiler didn't align a 24-byte static block)


#10

It would cause a crash on CPUs that do not handle word access on non-aligned address (x86 have no problems with that) -- according to http://www.ibm.com/developerworks/library/pa-dalign/ there could also be issues also with the atomical memory access of the spinlock if it is not correctly aligned

 


#11

Hmm. Ok, fair enough, I had forgotten about ARM. Even so, I'm sceptical that any compiler would actually fail to align a block like that, and I vaguely remember hearing that the C++11 spec explicitly says that larger blocks that aren't part of a larger structure should be aligned (I could be wrong about that..). But, since it's easy enough for me to make sure it's aligned, I will do!