c++ - Is it possible to extend the scope of a variable beyond the if statement without using pointers? -
i've got simple trace
class logs entering , exiting 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 want able enable/disable tracing. i'll 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 trace
instance scoped if statement
, therefore following output produced:
enter
exit
foo...
is there way right output in latter case, without using smart pointers? want have least overhead possible if tracing disabled.
p.s. please note real-world trace
class consists of few more lines, not "enter" , "exit".
p.s.2 due performance considerations, not want trace
instance created on stack if tracing disabled.
is there way right output in latter case, without using smart pointers? want have least overhead possible if tracing disabled.
modern compilers optimize simple smart pointers out entirely. should feel free use raii , smart pointers makes sense in code. code cleanly , , avoid micro-optimizations because never , make things worse.
Comments
Post a Comment