Aha, thanks for the pointer. It looks like the combination will do the trick. After playing around with your idea, this is what I came up with.
{
public:
ObserverData() : subject_limit(-1), id_counter(0), subject_type("Subject") {}
ObserverData
(const ObserverData
&other
) : QSharedData(other
) {}
PointerList<QObject> subject_list;
int subject_limit;
int id_counter;
};
class ObserverData : public QSharedData
{
public:
ObserverData() : subject_limit(-1), id_counter(0), subject_type("Subject") {}
ObserverData(const ObserverData &other) : QSharedData(other) {}
PointerList<QObject> subject_list;
int subject_limit;
int id_counter;
QString subject_type;
};
To copy to clipboard, switch view to plain text mode
class AbstractObserver
{
public:
AbstractObserver() { d = new ObserverData; }
AbstractObserver(const AbstractObserver &other) : d (other.d) {}
virtual ~AbstractObserver() {}
void detach() { d.detach(); }
virtual void attachSubject() {}
virtual void detachSubject() {}
private:
QExplicitlySharedDataPointer<ObserverData> d;
};
class AbstractObserver
{
public:
AbstractObserver() { d = new ObserverData; }
AbstractObserver(const AbstractObserver &other) : d (other.d) {}
virtual ~AbstractObserver() {}
void detach() { d.detach(); }
virtual void attachSubject() {}
virtual void detachSubject() {}
private:
QExplicitlySharedDataPointer<ObserverData> d;
};
To copy to clipboard, switch view to plain text mode
The above implementation will work very well for my needs. Thus, if an Observer wants to share the data with another observer it would just copy it. But when it wants to copy it and modify the data on its own it would call the detach() function.
I've been looking at the Employee example in the Qt Docs in detail which shows how to use SharedData along with QSharedDataPointer. However I have some doubts when the example is modified as above to use QExplicitlySharedDataPointer.
My doubt is related to the copy constructor. When using QExplicitlySharedDataPointer, is my copy constructor in the ObserverData class correct in the above code? I guess it is not necessary to initialize the internal variables since the data is shared explicitly. Or is it still necessary?
My compilation runs through fine, but I would like to understand it 100% before moving on.
Thanks for your time again,
Jaco
Bookmarks