实例方法中的静态变量
假设我有这个程序:(
class Foo {
public:
unsigned int bar () {
static unsigned int counter = 0;
return counter++;
}
};
int main ()
{
Foo a;
Foo b;
}
当然这个例子没有意义,因为我显然将“counter”声明为私有属性,但这只是为了说明问题)。
我想知道 C++ 在这种情况下的行为如何:bar() 方法中的变量“counter”对于每个实例都相同吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是的,
counter
将在可执行文件中Foo
类型的所有对象实例之间共享。只要您处于单线程环境中,它就会像共享计数器一样按预期工作。在多线程环境中,您将需要调试有趣的竞争条件:)。
Yes,
counter
will be shared across all instances of objects of typeFoo
in your executable. As long as you're in a singlethreaded environment, it'll work as expected as a shared counter.In a multithreaded environment, you'll have interesting race conditions to debug :).
通过“每个实例都相同”,您的意思是每个类实例之间都会共享该变量的一个实例,那么是的,这是正确的。该类的所有实例都将使用相同的变量实例。
但请记住,对于类变量,在许多情况下您必须考虑多线程之类的事情,这是一个完全不同的主题。
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.
来自C++ 编程语言(第 2 版),第 200 页,作者:Bjarne Stroustrup:
From The C++ Programming Language (2nd edition), page 200, by Bjarne Stroustrup:
您的示例距离可以编译和测试的内容只有几行:
输出如下所示:
所以是的,计数器在所有实例之间共享。
Your example was a couple lines away from being something you could compile and test:
The output looks like this:
So yes, the counter is shared across all instances.
您只需要掌握两件事:
You just need to grasp two things: