I have a problem with static vars/deque and objects. I am calculating some statistics for a real time data stream - mean, median, skew etc. As this is streaming data I make use of static vars, or in this version static container (deque). I have made several versions and they all exhibit the same problem. Even though I make two instances of the same method, the static deque seems to be shared. I have the following code (not the most efficient but readable):
double Mean(double& lastValue, const int& length)
{
static std::deque<double> buffer(length);
double sum = 0.0;
buffer.pop_back();
buffer.push_front(lastValue);
for (int j = 0; j < length; j++) {
try {
sum += buffer.at(j);
}
catch (const std::out_of_range& oor) {
std::cerr << "Out of Range error: " << j << " - " << oor.what() << '\n';
}
}
return length != 0 ? sum / length : 0;
}
If I make two instances of this like:
Stats s1, s2;
s1.Mean(streamData, 20);
s2.Mean(streamData, 30);
I get Out Of Range error.
Questions:
- What is causing the out_of_range exception?
- I might be wrong, but it seems like the static deque is shared between two objects - how is this possible?
Any help appreciated!