c++ - 为什么方法局部静态变量绑定到类而不是实例?
问题描述
在这个班
struct A
{
...
void method()
{
static x=0;
x++;
...
}
}
对于 A 的每个实例,对所有实例的调用method()
都会递增x
。
我希望只为调用x
的实例增加method()
,而不影响x
任何其他实例。这有效地将方法局部静态变量绑定到类,并且作为一个附带问题:为什么我不能有类级静态变量(只有 const 的),我希望它的行为与方法局部静态变量当前一样。
我知道我可以用一些额外的代码“修复”这个问题,但仍然想了解这种行为的原因。
对于那些想要查看行为的人的一些代码:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
inline void PRINTSTRING(const std::string &s) { std::cout << s; std::cout.flush(); }
template<typename...T> void say(T...t) { std::stringstream ss{}; (ss<<...<<t); PRINTSTRING(ss.str()); }
template<typename...T> std::string says(T...t) { std::stringstream ss{}; (ss<<...<<t); return ss.str(); }
template<typename...T> bool sayerr(T...t) { say("Error: ", t...); return false; }
struct A { std::string sa{"A"}; void who() { static int a=0; a++; say(says(sa, " a=", a, "\n")); }};
std::vector<A*> AList{};
void killas() { while (!AList.empty()) { auto it=AList.begin(); delete (*it); AList.erase(it); }}
A* newa(const std::string &s) { A *pA=new A; if (pA) { pA->sa=s; AList.push_back(pA); } return pA; }
void showas() { if (AList.empty()) say("-empty-\n"); else for (auto p:AList) p->who(); }
int main(int argc, const char *argv[])
{
say("\ntesting if a static var in a method is bound to instance or to class ...\n\nexpect 'empty'\n");
showas();
newa("one"); newa("two"); newa("three"); newa("four"); newa("five");
say("\nif bound to instance expect all 1's\n");
showas();
say("\nif bound to instance expect all 2's\n");
showas();
killas();
return 0;
}
解决方案
静态成员属于类而不是实例,方法局部静态各种也是这样。你只需要一个普通的类私人成员。
推荐阅读
- c++ - 在没有管理员权限的情况下安装 C++ 编译器
- r - 多个 gganimate 并排绘制
- java - 无法将 groovy 文件添加到源文件夹
- javascript - 无法创建所需的 UI
- redis - Jackson2HashMapper 不使用 Flatten=True 序列化日期
- python - 我可以逃避这个错误 Traceback(最近一次通话最后一次):文件“
",第 1 行,在 文件 ” ",第 2 行,在 data_entry 中 - python - 如何让这个功能更容易测试?
- php - 提交表单时,会话数据会变得很多
- php - PhpStorm 是否可以根据更改的项目文件夹结构自动更改命名空间和用途?
- javascript - 如何在 javascript 的 addEventListener 函数中添加函数?