I've got a simple Trace class that logs entering and exiting a method:
#include <iostream>
class Trace
{
public:
Trace() {std::cout << "Enter" << std::endl;}
~Trace()
{
std::cout << "Exit" << std::endl;
}
};
void foo()
{
Trace trace;
std::cout << "foo..." << std::endl;
}
int main()
{
foo();
return 0;
}
output:
Enter
foo...
Exit
Now I want to be able to enable/disable tracing. So I'll do something like this:
#include <iostream>
class Trace
{
public:
Trace() {std::cout << "Enter" << std::endl;}
~Trace()
{
std::cout << "Exit" << std::endl;
}
static bool enabled;
};
bool Trace::enabled = false;
void foo()
{
if(Trace::enabled)
Trace trace;
std::cout << "foo..." << std::endl;
}
int main()
{
Trace::enabled = true;
foo();
return 0;
}
The problem is that now the trace instance is scoped to the if statement and therefore the following output is produced:
Enter
Exit
foo...
Is there any way to get the right output in the latter case, without using smart pointers? I want to have the least overhead possible if tracing is disabled.
Aucun commentaire:
Enregistrer un commentaire