QMutexLocker and return value [SOLVED]
-
Hi,
I have a general question about QMutexLocker. What happens when I leave a function returning a "protected" value.
I usually use QMutex as follows, where m_value is the protected value:
@int getValue()
{
m_mutex.lock();
int v = m_value;
m_mutex.unlock();return v;
}
@Now with QMutexLocker:
@int getValue()
{
QMutexLocker( m_mutex );return m_value;
}@But what happens when m_value is returned? Is m_value returned before QMutexLocker is destroyed or vice versa? Is m_value still safe?
regards
Oliver -
I think return m_value creates a copy of the variable, and the mutex locker goes out of scope later (after the return statement). So your solution stvokr should work fine (and is less to type than what topse proposed).
-
"Here":http://stackoverflow.com/questions/25865210/c-function-end-and-local-destruction-order is the same question, albeit returning a string, on Stackoverflow.
The local variables are destructor in the reverse order they are created on the stack. The returned value is either a temporary copy or constructor in place where it is assigned, again a copy in case of an int. Either way, QMutexLocker object, which is created before the temporary, gets destructed last.
By the way there is a bug in your sample code. Since your QMutexLocker is not a named variable, it gets destructed at the ';' on the line its created. You need to name it so that it survives the function scope.