我试图通过在代码执行期间打印出静态变量和非静态变量的内存位置来理解 C++ 静态变量和非静态变量之间的差异。下面是我的代码:
#include <iostream>
void testStatic(int currNum)
{
static int counter;
std::cout << "Address of counter: " << &counter << "\n";
counter += currNum;
std::cout << "counter: " << counter << "\n";
}
void testNonStatic(int currNum)
{
int nsCounter;
std::cout << "Address of Non-static counter: " << &nsCounter << "\n";
nsCounter += currNum;
std::cout << "Non-static counter: " << nsCounter << "\n\n";
}
int main()
{
for(int i = 0; i < 5; i++)
{
testStatic(i);
testNonStatic(i);
}
}
根据我的理解,静态变量静态变量的内存分配在我们的例子中只会发生一次,其中变量的地址在整个程序执行期间保持不变。
对于非静态变量(nsCounter)的情况,它的行为似乎也像静态变量(相同的存储,计数器在整个循环中不断更新)。
每次调用函数时是否需要将 nsCounter 初始化为 0 以使其成为非静态?
Address of counter: 0x558b476c9158
counter: 0
Address of Non-static counter: 0x7fff20471894
Non-static counter: 0
Address of counter: 0x558b476c9158
counter: 1
Address of Non-static counter: 0x7fff20471894
Non-static counter: 1
Address of counter: 0x558b476c9158
counter: 3
Address of Non-static counter: 0x7fff20471894
Non-static counter: 3
Address of counter: 0x558b476c9158
counter: 6
Address of Non-static counter: 0x7fff20471894
Non-static counter: 6
Address of counter: 0x558b476c9158
counter: 10
Address of Non-static counter: 0x7fff20471894
Non-static counter: 10
期望非静态计数器的输出为 0,1,2,3,4,我们在这里得到 0,1,3,6,10。
未初始化的非静态变量,其初始值未定义。只需初始化它即可。