My question is different from Static variables in member functions.
class A {
public:
void foo() {
B b(params_); // It takes lots of time to construct b. b is only used in foo().
// do something with b
return;
}
private:
int params_;
};
int main() {
A a1(params1), a2(params2);
a1.foo(); // call 1
a1.foo(); // call 2
a2.foo(); // call 3
}
I want b
to be same in call 1 & call 2 and constructed only once and should be seen in foo() only. However b
should have different value in call 2 & call 3 due to different value of params_ in a1
and a2
. How should I declare b
?
- static variable in foo(): b has same value across different instances a1, a2. It doesn't meet my requirement.
- local variable in foo(): b is constructed every time foo() is called. It doesn't meet my requirement.
- member variable of class A: b can be seen by other member functions of A. It doesn't meet my requirement.
- other good choice?