11

Let's say I have this program:

class Foo {
 public:
    unsigned int bar () {
        static unsigned int counter = 0;
        return counter++;
    }
};

int main ()
{
    Foo a;
    Foo b;
}

(Of course this example makes no sense since I'd obviously declare "counter" as a private attribute, but it's just to illustrate the problem).

I'd like to know how C++ behaves in this kind of situation: will the variable "counter" in the bar() method be the same for every instance?

4

5 回答 5

10

是的,counterFoo在可执行文件中类型对象的所有实例之间共享。只要您在单线程环境中,它就会像共享计数器一样按预期工作。

在多线程环境中,您将有有趣的竞争条件来调试:)。

于 2010-01-29T18:18:50.190 回答
2

By "be the same for every instance" you mean there will be one instance of this variable shared across each class instance, then yes, that's correct. All instances of the class will use that same variable instance.

But keep in mind that with class variables you have to take things like multi-threading into account in many cases, which is a whole different topic.

于 2010-01-29T18:13:09.813 回答
1

摘自Bjarne Stroustrup的 The C++ Programming Language (2nd edition),第 200 页:

除了 [plain] 函数(§7.1.2)和类(§10.2.4)之外,不要使用静态。

于 2010-01-29T18:21:34.243 回答
1

您的示例与您可以编译和测试的东西相距几行:

#include <iostream>
using namespace std;
class Foo {
 public:
    unsigned int bar () {
        static unsigned int counter = 0;
        return counter++;
    }
};

int main ()
{
    Foo a;
    Foo b;

    for (int i=0; i < 10; i++)
      cout<<i<<". "<<a.bar()<<" / "<<b.bar()<<endl;
}

输出如下所示:

0. 1 / 0
1. 3 / 2
2. 5 / 4
3. 7 / 6
4. 9 / 8
5. 11 / 10
6. 13 / 12
7. 15 / 14
8. 17 / 16
9. 19 / 18

所以是的,计数器在所有实例之间共享。

于 2010-01-29T18:56:40.210 回答
0

你只需要掌握两件事:

  1. 静态变量存储在执行程序的静态区域(与全局变量相同)。
  2. 范围受括号的一般规则限制。此外,静态变量具有内部链接。
于 2010-01-29T18:22:01.840 回答