首页 > 解决方案 > 为什么方法局部静态变量绑定到类而不是实例?

问题描述

在这个班

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++classstaticinstancelanguage-design

解决方案


静态成员属于类而不是实例,方法局部静态各种也是这样。你只需要一个普通的类私人成员。


推荐阅读