I analyze a class with unique_ptr member. That member may be used from different threads. There is also a method which destroys that member:
void uninitialize()
{
std::unique_ptr<Worker> worker;
{
std::lock_guard<std::mutex> guard(mtx_);
worker = std::move(worker_);
}
}
I wonder what is purpose of that impl. Is there any difference between the above and the following implementation? :
void uninitialize()
{
std::lock_guard<std::mutex> guard(mtx_);
worker_.reset();
}
Worker doesn't define move constructor.
The difference is that in the first snippet, the mutex will only be held for long enough for worker
to take ownership of the object that worker_
owns; the destruction of that object will be unguarded. In the second snippet, the mutex will not be released until .reset()
completes, which means it is held while the object is being destroyed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With