I want to use unique_ptr
in a method. I want to rely on the fact that it is destroyed at the closing brace of the method (if that is indeed true).
The reason why I want to rely on this fact is that I want to write a simple class for logging that says when it has entered/exited a method, something like:
class MethodTracing
{
string _signature;
public:
MethodTracing(string signature)
{
_signature=signature;
BOOST_LOG_TRIVIAL(trace) << "ENTERED " << _signature ;
}
~MethodTracing()
{
BOOST_LOG_TRIVIAL(trace) << "EXITED " << _signature;
}
};
I can then use it like so:
void myMethod( )
{
auto _ = unique_ptr<MethodTracing>(new MethodTracing(__FUNCSIG__) ) ;
/// ...
}
Is it true (and consistent) that a unique_ptr
, when created in a method, is destroyed at the end of the method (assuming it's not passed around).
Are there any other hidden (or otherwise!) pitfalls that I should be aware of?
Update:
As most of the answers suggested, I could have used local variable scoping. I tried this with MethodTracing(__FUNCSIG__);
, but of course, I didn't assign a local variable! so it immediately went out of scope. I thought the runtime was being clever, but no, it was me being stupid (too long in C#!)