C++ 成员函数中的静态变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6223355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Static variables in member functions
提问by monofonik
Can someone please explain how static variables in member functions work in C++.
有人可以解释一下成员函数中的静态变量如何在 C++ 中工作。
Given the following class:
鉴于以下类:
class A {
void foo() {
static int i;
i++;
}
}
If I declare multiple instances of A
, does calling foo()
on one instance increment the static variable i
on all instances? Or only the one it was called on?
如果我声明 的多个实例A
,调用foo()
一个实例是否会增加i
所有实例上的静态变量?还是只有它被调用的那个?
I assumed that each instance would have its own copy of i
, but stepping through some code I have seems to indicate otherwise.
我假设每个实例都有自己的 副本i
,但逐步执行我拥有的一些代码似乎另有说明。
回答by iammilind
Since class A
is a non-template class and A::foo()
is a non-template function. There will be only one copy of static int i
inside the program.
因为class A
是一个非模板类并且A::foo()
是一个非模板函数。static int i
程序内部将只有一份副本。
Any instance of A
object will affect the same i
and lifetime of i
will remain through out the program. To add an example:
A
对象的任何实例都将影响相同,i
并且i
将在整个程序中保持生命周期。添加示例:
A o1, o2, o3;
o1.foo(); // i = 1
o2.foo(); // i = 2
o3.foo(); // i = 3
o1.foo(); // i = 4
回答by 6502
The keyword static
unfortunately has a few different unrelated meanings in C++
static
不幸的是,关键字在 C++ 中有一些不同的不相关的含义
When used for data members it means that the data is allocated in the classand not in instances.
When used for data inside a function it means that the data is allocated statically, initialized the first time the block is enteredand lasts until the program quits. Also the variable is visible only inside the function. This special feature of local statics is often used to implement lazy construction of singletons.
When used at a compilation unit level (module) it means that the variable is like a global (i.e. allocated and initialized before
main
is run and destroyed aftermain
exits) but that the variable will not be accessible or visible in other compilation units.
当用于数据成员时,这意味着数据是在类中而不是在实例中分配的。
当用于函数内部的数据时,它意味着数据是静态分配的,在第一次进入块时初始化并持续到程序退出。此外,该变量仅在函数内部可见。局部静态的这种特殊功能通常用于实现单例的惰性构造。
当在编译单元级别(模块)使用时,这意味着该变量就像一个全局变量(即在
main
运行之前分配和初始化并在main
退出之后销毁),但该变量在其他编译单元中将不可访问或可见。
I added some emphasis on the part that is most important for each use. Use (3) is somewhat discouraged in favor of unnamed namespaces that also allows for un-exported class declarations.
我在每次使用中最重要的部分添加了一些重点。使用 (3) 有点不鼓励使用未命名的命名空间,它也允许未导出的类声明。
In your code the static
keyword is used with the meaning number 2 and has nothing to do with classes or instances... it's a variable of the functionand there will be only one copy of it.
在您的代码中,static
关键字与含义编号 2 一起使用,与类或实例无关……它是函数的变量,并且只有一个副本。
As correctly iammilindsaid however there could have been multiple instances of that variable if the function was a template function (because in that case indeed the function itself can be present in many different copies in the program). Even in that case of course classes and instances are irrelevant... see following example:
正如iammilind所说的那样,如果函数是模板函数,则该变量可能有多个实例(因为在这种情况下,函数本身确实可以存在于程序中的许多不同副本中)。即使在这种情况下,课程类和实例也无关紧要……请参见以下示例:
#include <stdio.h>
template<int num>
void bar()
{
static int baz;
printf("bar<%i>::baz = %i\n", num, baz++);
}
int main()
{
bar<1>(); // Output will be 0
bar<2>(); // Output will be 0
bar<3>(); // Output will be 0
bar<1>(); // Output will be 1
bar<2>(); // Output will be 1
bar<3>(); // Output will be 1
bar<1>(); // Output will be 2
bar<2>(); // Output will be 2
bar<3>(); // Output will be 2
return 0;
}
回答by Saurabh Raoot
Static variables inside functions
函数内的静态变量
Static variable is created inside a function is stored on program's static memory not on the stack.
Static variable initialization will be done on the first call of the function.
Static variable will retain the value in multiple function calls
Lifetime of the static variable is Program
静态变量是在函数内部创建的,存储在程序的静态内存中而不是堆栈中。
静态变量初始化将在第一次调用函数时完成。
静态变量将在多个函数调用中保留该值
静态变量的生命周期是 Program
Examples
例子
#include <iostream>
using namespace std;
class CVariableTesting
{
public:
void FuncWithStaticVariable();
void FuncWithAutoVariable();
};
void CVariableTesting::FuncWithStaticVariable()
{
static int staticVar;
cout<<"Variable Value : "<<staticVar<<endl;
staticVar++;
}
void CVariableTesting::FuncWithAutoVariable()
{
int autoVar = 0;
cout<<"Variable Value : "<<autoVar<<endl;
autoVar++;
}
int main()
{
CVariableTesting objCVariableTesting;
cout<<"Static Variable";
objCVariableTesting.FuncWithStaticVariable();
objCVariableTesting.FuncWithStaticVariable();
objCVariableTesting.FuncWithStaticVariable();
objCVariableTesting.FuncWithStaticVariable();
objCVariableTesting.FuncWithStaticVariable();
cout<<endl;
cout<<"Auto Variable";
objCVariableTesting.FuncWithAutoVariable();
objCVariableTesting.FuncWithAutoVariable();
objCVariableTesting.FuncWithAutoVariable();
objCVariableTesting.FuncWithAutoVariable();
objCVariableTesting.FuncWithAutoVariable();
return 0;
}
Output :
输出 :
Static Variable
静态变量
Variable Value : 0
Variable Value : 1
Variable Value : 2
Variable Value : 3
Variable Value : 4
变量值:0
变量值:1
变量值:2
变量值:3
变量值:4
Auto Variable
自动变量
Variable Value : 0
Variable Value : 0
Variable Value : 0
Variable Value : 0
Variable Value : 0
变量值:0
变量值:0
变量值:0
变量值:0
变量值:0
回答by 0xbadf00d
Simplified answer:
简化答案:
Static variables, regardless whether they are members of a (non-templated) class
or a (non-templated) function, behave - technically - like a global label which scope is limited to the class
or function.
静态变量,无论它们是(非模板化)class
还是(非模板化)函数的成员,在技术上都表现得像一个全局标签,其作用域仅限于class
or 函数。