Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different ways to destructing unique_ptr

Tags:

c++

c++11

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.

like image 602
Irbis Avatar asked Dec 31 '22 18:12

Irbis


1 Answers

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.

like image 67
Brian Bi Avatar answered Jan 12 '23 23:01

Brian Bi