I'm trying to write a very simple memory size counter using a volatile static variable to keep track of the allocations inside a certain class.
I've written the class' destructor to atomically decrement this static volatile integer, but the compiler (VC VS2010) optimizes it away (inlining it, although it should not - the variable inside the destructor is volatile, perhaps it should take that into account..?). Instead, that destructor seems to never get called (i.e. the class's members are disposed off correctly, but apparently not using the custom destructor).
I can't write code snippets (it's from a "classified" source code). But, basically, it all looks like this:
the header:
class CSomething
{
CObject m_object;
...
public:
static volatile int ms_counter;
~CSomething();
}
the .cpp:
CSomething::CSomething()
{
DoStuffWith(m_object);
AtomicAdd(ms_counter, m_object.GetTotalSize());
}
CSomething::~CSomething()
{
AtomicDecrement(ms_counter, m_object.GetTotalSize());
}
To resume: the ~CSomething()
destructor gets inlined or optimized away (?) since I can't place a breakpoint inside it. The value of ms_counter
only increases, but never decreases (although the m_object
's destructor clearly gets called). (NO, I cannot decrement the counter inside of m_object
's own destructor :( ).
The question, again is: what could really happen? How can I avoid this issue? Forcing no inline via compiler flags does not do the trick either.. (and I wouldn't want it not to be inlined since it might damage the performance).