gpt4 book ai didi

c++ - Qt/C++ 共享变量和跨类实例的可见性

转载 作者:太空宇宙 更新时间:2023-11-04 11:48:33 24 4
gpt4 key购买 nike

我正在努力解决一些非常基本的问题,我希望有人可以帮助澄清。以这个伪 C++ 代码为例:

class T {
public
QMutex M;
int I;
}
  1. 如果我将此类实例化三次(作为 3 个线程),是否有 3 个独立且不相关的 M 和 I 变量?还是所有 3 个实例共享相同的 M 和 I 变量?

  2. 如果一个类有多个可重入方法(例如:槽),并且它们访问 M 或 I,那么它们访问的是该类的一个实例的 M 还是 I?

  3. 如何为类的每个实例赋予它自己的变量(其他实例无法访问)

最佳答案

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?

分开是因为这些变量分配在栈上而不是堆上。如果您在不同的类实例中使用指向同一内存的指针,则可以通过堆对象共享内存值。

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?

是的,如果您在类实例上使用插槽,除非您明确尝试访问其他类实例,否则它们将访问这些插槽。

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

就像你上面写的一样。 :-) 虽然请注意,您编写了公共(public)可访问性,因此最终您可以通过任何实例从任何实例访问它们,但这可能不是您要引用的内容。

关于c++ - Qt/C++ 共享变量和跨类实例的可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19164216/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com