Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Post History
No, such an operation is not safe. The documentation of std::unique_lock in the standard states that it's UB for the mutex do be destroyed while the lock still has a pointer to it. However, there ...
Answer
#2: Post edited
- No, such an operation is not safe. The documentation of `std::unique_lock` in the standard states that it's UB for the mutex do be destroyed while the lock still has a pointer to it.
- However, there is a way to dissociate the mutex from the lock: calling `release` on the lock. That resets the lock's internal mutex pointer to null. So the code would be valid like this:
- ```
- {
- std::unique_ptr<std::mutex> mutex = std::make_unique<std::mutex>();
- std::unique_lock<std::mutex> lock(*mutex);
- lock.unlock();
- lock.release();
- mutex.reset();
- }
```
- No, such an operation is not safe. The documentation of `std::unique_lock` in the standard states that it's UB for the mutex do be destroyed while the lock still has a pointer to it.
- However, there is a way to dissociate the mutex from the lock: calling `release` on the lock. That resets the lock's internal mutex pointer to null. So the code would be valid like this:
- ```
- {
- std::unique_ptr<std::mutex> mutex = std::make_unique<std::mutex>();
- std::unique_lock<std::mutex> lock(*mutex);
- lock.unlock();
- lock.release();
- mutex.reset();
- }
- ```
- ---
- Here are the relevant standard quotes from C++2a (N4680) 32.5.4.3. [thread.lock.unique] (`pm` is an exposition-only pointer to the mutex associated with the lock):
- > 32.5.4.3/1 The behavior of a program is undefined if the contained pointer `pm` is not null and the lockable object pointed
- to by `pm` does not exist for the entire remaining lifetime (6.7.3) of the `unique_lock` object.
- > 32.5.4.3.3
- >
- > ```
- > mutex_type* release() noexcept;
- > ```
- >
- > 2 *Returns:* The previous value of `pm`.
- >
- > 3 *Postconditions:* `pm == 0` and `owns == false`.[]()[]()
#1: Initial revision
No, such an operation is not safe. The documentation of `std::unique_lock` in the standard states that it's UB for the mutex do be destroyed while the lock still has a pointer to it. However, there is a way to dissociate the mutex from the lock: calling `release` on the lock. That resets the lock's internal mutex pointer to null. So the code would be valid like this: ``` { std::unique_ptr<std::mutex> mutex = std::make_unique<std::mutex>(); std::unique_lock<std::mutex> lock(*mutex); lock.unlock(); lock.release(); mutex.reset(); } ```