PDA

View Full Version : Access to shared map between parent - children



atomic
10th August 2015, 18:42
Hi,

In my applications I have class which contains QMap, and several child classes which execute tasks on the variables from this map.

Now I would ask you, which way for communication between parent - child is a better in this case:
- cast the parent pointer to the right type and then call parent function
- store the pointer to the parent somewhere in the child when receiving it in the constructor

or use signals and slots - send signal to parent with key as argument and then wait for value from map?
But with signals and slots is a problem, because when child send signal with key to parent class then parent should send signal with value to only specific child object but signal is send to all child.

Which way you choose when you have a similar problem?
Thanks,

anda_skoa
10th August 2015, 19:00
Either keep a pointer to the parent or share the map.

Cheers,
_

atomic
10th August 2015, 19:26
I can not share the map because it must be protected from simultaneously access at the same time something like this



int accessToMap(QString key)
{
QMutexLocker locker(&mutex);
//.......

return mMap.value(key);
}



Either keep a pointer to the parent or share the map.

Do you mean keep pointer inside class and initialize it inside constructor?



class Child {

};

class Parent {

public:
Parent(Child * child) : mChild(child) {};
private:
Child * mChild;
};


or use something like that



class Parent : public QObject{

public:
Parent() {
child = new Child(this);
}

int accessToMap(QString key) {};

private:
Child *child;
};

class Child : public QObject{

public:
Child(QObject *parent) : QObject(parent){};

void accessToMap(QString key ) {
Parent* parent = qobject_cast<Parent*>(this->parent());
parent->accessToMap("somekey");
}
};

anda_skoa
10th August 2015, 21:13
Ah, you didn't say the the children are used by different threads, nor that the map is modified during runtime.

You could still pass a synchronized container (e.g. wrapper around the map) but option 1 (explicitly typed member) looks good as well.

Cheers,
_

atomic
10th August 2015, 22:24
But it looks like that, I store duplicate a pointer to parent, because QObject already has it and return it via parent() method. I am right?

Whether first method is better in multithreading app from that



Parent* parent = qobject_cast<Parent*>(this->parent());
parent->accessToMap("somekey");

or it is the same?

Thanks,

anda_skoa
10th August 2015, 23:24
Sure, if you want to lose the type safety or incure the runtime overhead of a checked cast, that's your choice.

Cheers,
_