I have a statistics manager that examines my application performance by measuring the time it takes for a method to execute. It's usage is like this:
myStatManager.StartStat("Rendering");
Render();
myStatManager.StopStat("Rendering");
The output to screen will tell me how long that method took.
For convenience, I have written a dummy object, that calls these two methods as the object is created and destroyed. This allows me to use C++ scope rules to my advantage and only type the stat tracking lines once instead of twice as above.
class ScopedStat
{
string label;
ScopedStat(string inLabel): label(inLabel) { myStatManager.StartStat(label); }
~ScopedStat() { myStatManager.StopStat(label); }
}
The expected usage is as follows:
{
ScopedStat("Rendering");
Render();
}
However, this does not work, as perhaps the compiler or something has optimized the ScopedStat object out. The reported time is a fraction of a millisecond and nowhere near the time it should take to render. My question is, why does this way not work? Does this object not get destroyed at the end of scope?
Edit: I have found a workaround:
{
ScopedStat ss("Rendering");
Render();
}
This works as intended--the object gets destroyed only at the end of the curly bracket. Though, I'd still like to know why.
Note: Using Microsoft Visual Studio 2008 C++;
Edit2: Ah, i understand now that unless i bind my object to a variable it is destroyed after the expression is evaluated. Thanks for all your help.
Does anyone know why C++ is written this way? What use is a temporary variable if it gets destroyed immediately?