Reputation: 293
Given the class:
class A {
Public:
void foo() {
static int i;
i++;
}
};
How would you change it to prevent i
from changing between instances following this example:
A o1, o2, o3;
o1.foo(); // i = 1
o2.foo(); // i = 1
o3.foo(); // i = 1
o1.foo(); // i = 2
i.e. allocate memory for i
on every instance.
EDIT:
Yes, you can add i
as an instance variable, but what if you need these counters in various (independent) functions ? I am looking to limit the scope of the variable only to the function ("in member functions"). It would seem awkward to add variables such as i
, c
, counter
, counter_2
to the class if you need various counters, would it not ?
Upvotes: 3
Views: 1768
Reputation: 4201
In circumstances where declaring data members become costly(need for sparse members that are not used so often), An instance indepent collection - normally an associative one - may come in handy. Knowing nothing more about the OP's intention, std::map
family of classes can be used as first speculation. We need to have one counter per visited object in A::foo
, but not for unvisited instances(i.e. A
instances not calling A::foo
). This was the the simplest first solution I came up with:
void A::foo(){
static std::map<A*,std::size_t> i;
++i[this];
//...
};
Upon call to std::map::operator[]
on an object not in the map, the associated value is default constructed in a memory location already zeroed by the allocator( in short words 1st-timers are automatically initialized to 0).
Upvotes: 2
Reputation: 234665
class A
{
public:
int i = 0;
void foo(){
++i;
}
};
is the normal way: i
is now a member variable of the class. Clearly you don't want to use static
.
Upvotes: 5