Question

I'm struggling with something very basic that I'm hoping that someone can help clarify. Take for example this pseudo C++ code:

class T {
  public
    QMutex M;
    int I;
}
  1. If I instantiate this class three times (as 3 threads), are there 3 separate and unrelated M and I variables? Or do all 3 instances share the same M and I variable?

  2. If a class has several re-entrant methods (eg: slots), and they access M or I, are they accessing the M or I of that one instance of the class?

  3. How can I give each INSTANCE of the class it's own variable (not accessible to other instances)

Was it helpful?

Solution

If I instantiate this class three times (as 3 threads), are there 3 separate and unrelated M and I variables? Or do all 3 instances share the same M and I variable?

Separate because these variables are allocated on the stack as opposed to heap. You could share memory values by heap objects if you use pointers that point to the same memory in different class instances.

If a class has several re-entrant methods (eg: slots), and they access M or I, are they accessing the M or I of that one instance of the class?

Yes, if you use the slots on the class instance, they will access these unless you explicitly try to access other class instances.

How can I give each INSTANCE of the class it's own variable (not accessible to other instances)

Just like you wrote above. :-) Although, note that you wrote public accessibility so eventually you could access them by any instance from any instance, but this is probably not what you are trying to refer to.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top