实例方法中的静态变量 [英] Static variables in instance methods

查看:159
本文介绍了实例方法中的静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个程式:

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

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

(当然这个例子没有意义,因为我明显声明counter 作为私有属性,但它只是为了说明问题)。

(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).

我想知道C ++在这种情况下的行为:将变量counter

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?

推荐答案

是, code>将在您的可执行文件中的 Foo 类型的所有实例之间共享。

Yes, counter will be shared across all instances of objects of type Foo in your executable. As long as you're in a singlethreaded environment, it'll work as expected as a shared counter.

在多线程环境中,你会有一些有趣的竞态条件, debug:)。

In a multithreaded environment, you'll have interesting race conditions to debug :).

这篇关于实例方法中的静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆