You said, in a comment:
I do want a variable that is specific for each instance of a class
That's precisely what an instance variable is (a.k.a. a per-instance member).
static
members and function local variables are not specific to each instance of a class! They are either completely global (one instance per entire executable), or are per-thread if you use C++11 and declare them thread_local
.
You absolutely need a member variable. That's the only way to guarantee that the variable will be specific for each instance of the class.
You might argue that you create a dedicated thread per each instance of the class. First of all, it's likely that you shouldn't be doing that. Secondly, if you ever change your mind, and stop creating a per-class thread and, say, use a thread pool instead, your code will instantly break.
So, the proper and straightforward thing is to have it as an instance variable (as opposed to a class variable):
// OK - instance variable
class C { int var; };
// WRONG - class variable and lookalikes
class C { static int var; };
class C { void foo() { static int var; } };
// WRONG - thread variable, but **not** instance variable
class C { static thread_local int var; };
class C { void foo() { static thread_local int var; } };
If you want, you can indicate your intent by including the method's name in the variable name:
class C {
int foo_var;
C() : foo_var(0) {}
void foo() { ... }
};
Finally, if you're OK with a bit more typing, you can use a member wrapper to enforce the scope it's used in:
#include <utility>
#include <cassert>
template <typename T, typename Member, Member member>
class ScopedMember {
T data;
public:
explicit ScopedMember(const T & d) : data(d) {}
explicit ScopedMember(T && d) : data(std::move(d)) {}
ScopedMember() {}
template <Member m, void(*)(char[member == m ? 1 : -1]) = (void(*)(char[1]))0>
T & use() { return data; }
template <Member m, void(*)(char[member == m ? 1 : -1]) = (void(*)(char[1]))0>
const T & use() const { return data; }
};
class C {
public:
C() : m_foo(-1) {}
void granted() {
auto & foo = m_foo.use<&C::granted>();
foo = 5;
assert(m_foo.use<&C::granted>() == 5);
}
void rejected() {
#if 0
// Won't compile
auto & foo = m_foo.use<&C::rejected>();
#endif
}
private:
ScopedMember<int, void(C::*)(), &C::granted> m_foo;
};
int main()
{
C().granted();
return 0;
}
local variable
not static, no member, just a local variable in the method-block!!! - Thread-locals like mentioned in the other answers can lead to a bunch of problems with memory leaks and similar in big applications, so should only be used when really necessary!