To avoid reporting too many errors repeatedly, I use the std::map
container to cache the error code and corresponding channel number, on the other hand, for the same error occurred on the same channel, I only send it to D-Bus one time in a fixed cycle time.
Here is the C++ code. The static local variable cache
will eat many memories if the Send()
function is called quickly with different channel and error numbers.
The question is, how the memory of cache
will be allocated? On heap or stack? If the stack, what's the maximum size of cache
?
void Send(int ch, int err, const std::string & msg) {
const std::chrono::milliseconds cycle(m_reportCycleMS);
static std::map<std::pair<int, int>, std::chrono::time_point<std::chrono::steady_clock>> cache;
std::pair<int, int> key(ch, err);
auto now = std::chrono::steady_clock::now();
if (cache.find(key) == cache.end()) {
cache[key] = now;
m_queuedDBus.Send(err, msg);
}
else if ((now - cache[key]) > cycle) {
cache.erase(key);
}
}
The cache
variable itself will have static duration, and will be allocated similarly to a global variable at file scope.
But cache
itself is only the "header" of the std::map
.
It's size is implementation dependant, but it is a compile time constant and relative small (you can use sizeof
to get it - see demo).
The actual data in the std::map
will be allocated as std::map
does it always - regardless of where cache
itself is allocated. Typically (by default) it will be on the heap and the max size will depend on your system/memory etc.
Note that you can control how and where std::map
is allocating the data via the Allocator
template parameter.