1

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)

László Papp
  • 51,870
  • 39
  • 111
  • 135
TSG
  • 4,242
  • 9
  • 61
  • 121

1 Answers1

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?

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.

László Papp
  • 51,870
  • 39
  • 111
  • 135
  • Thans Laszlo - you are answering a lot of my questions! Does this mean if I want to create a QMutex variable M to be shared by many instances of class T, I would have to make M a static variables? – TSG Oct 03 '13 at 16:39
  • @Michelle: Yep. Hope you do not hate me that I run for so many of your questions, and perhaps you would like to hear someone else at times. :-) – László Papp Oct 03 '13 at 16:41