When an automatic variable goes out of scope, in what order does the operation occur?

I create a simple { mutex, value } pair as follows, and I would like to check with C ++ lawyers if my use case is well defined.

Tool definition

 template<typename T, class mutex> class Locker; template<typename T, class mutex> class Mutexed { T _value; mutex _mutex; friend class Locker<T, mutex>; public: Mutexed() {} Mutexed(const T& init) : _value(init) {} Mutexed(const Mutexed<T>& other) : _value(other._value) {} }; template<typename T, class mutex> class Locker { Mutexed<T, mutex>& _mutexed; public: Locker(Mutexed<T, mutex>& mutexed) : _mutexed(mutexed) { _mutexed.mutex.lock(); } ~Locker() { _mutexed.mutex.unlock(); } const T& operator*() const { return _mutexed.value; } T& operator*() { return _mutexed.value; } }; 

Use case

 Mutexed<int, MyMutex> answer(42); int getAnswer() { Locker<int> lock(answer); return *lock; } 

My concern

Since *lock , id est const T& operator*() const { return _mutexed.value; } const T& operator*() const { return _mutexed.value; } returns a link to answer._value , a copy is made from int& to int . But since the lock goes out of scope during the return: what copy and unlock of the mutex will happen first ?

TL; DR

I want my usecase not to be UB xor?

 const int result = *lock; return result; 
+5
source share

Source: https://habr.com/ru/post/1266591/


All Articles