Reputation: 1491
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.
Upvotes: 4
Views: 305
Reputation: 31465
In the first example, worker
ends up owning the unique_ptr
(until it goes out of scope, without the lock held) In the second it is just destroyed (while the lock is held).
Upvotes: 0
Reputation: 119184
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.
Upvotes: 9