I have 3 different classes(A, B, C) that each have a shared_ptr to a shared object(object X). What I want to do is to give object X information about who is pointing at it. For example, if there were no A objects pointing to it, it wouldn’t need to calculate data that’s only used by A classes when it is updated. And object X could keep a vector of pointers to the C objects that point at it so it can call a function on them when some data relevant to C objects has been updated(but the C objects still point at it to query other data from it).
What I was thinking of doing is creating a wrapper class for the shared_ptr on each class that would invoke pointers to functions on X whenever the wrapper is constructed/assigned/destructed(all of the same cases that increment/decrement the reference count on X). Here’s the idea in code:
class A
{
public:
A() : m_ptr(&X::IncrementACount, &X::DecrementACount) { }
void SetX( const std::shared_ptr<X> &ptr ) { m_ptr = ptr; }
private:
shared_ptr_wrapper0<X> m_ptr;
};
class B
{
public:
B() : m_ptr(&X::IncrementBCount, &X::DecrementBCount) { }
void SetX( const std::shared_ptr<X> &ptr ) { m_ptr = ptr; }
private:
shared_ptr_wrapper0<X> m_ptr;
};
class C
{
public:
C() : m_ptr(this, &X::StoreCPointer, &X::RemoveCPointer) { }
void SetX( const std::shared_ptr<X> &ptr ) { m_ptr = ptr; }
private:
shared_ptr_wrapper1<X, const C*> m_ptr;
};
Both A and B have a wrapped smart pointer with Increment/Decrement functions specified that take no arguments. When the wrapped smart pointer gets set/cleared/etc, those functions will be called on the X object it contains and increment/decrement the A/B counters.
C has a wrapped smart pointer with one argument(of type const C* ). When it gets set/cleared/etc, the functions on it will be called with the data that was stored on it by C’s constructor(the this pointer) and will add or remove it from the vector on object X.
So my main question is this a good idea? Is there a better way to accomplish this idea of keeping track of who is pointing to an object? Is there a specific name for this kind of idea(I can’t imagine I’m the first to try something like this, but I didn’t find anything when searching for it so maybe I just don’t know the right name to look for…)
Thank you.
A simpler approach would be observer pattern, aka publish/subscriber. See http://en.wikipedia.org/wiki/Observer_pattern. Your X object is the publisher and can offer 3 different interfaces to be observed. Your A, B, and C objects are the subscribers and they sign up to be notified of changes. Each Observer is responsible for adding and removing itself from X’s subscription lists. When something changes in X, everyone on the appropriate subscription lists is notified via their interface.