Lets say I have two local objects. When the function returns, is it guaranteed which one will go out of the scope first?
For example:
I have a class like this:
class MutexLock
{
/* Automatic unlocking when MutexLock leaves a scope */
public:
MutexLock (Mutex &m) { M.lock(); }
~MutexLock(Mutex &m) { M.unlock(); }
};
This is a very common trick used to automatically release the mutex when going out of scope. But what if I need two mutexes in the scope?
void *func(void *arg)
{
MutexLock m1;
MutexLock m2;
do_work();
} // m1 and m2 will get unlocked here. But in what order? m1 first or m2 first?
This really can't cause any deadlock. But there may be instances in which order of releasing the resource might be useful to the user. In that case is it important to be explicit rather than relying on destructors?
Also, can destruction be delayed by the compiler in any case? What I mean is
func()
{
{
foo f();
} ---------> Can compiler choose to not destroy f here, rather do it at the time when func() is returning.
}
// m1 and m2 will get unlocked here. But in what order? m1 first or m2 first?
The destructors will be called in the reverse order of construction: m2
then m1
.
In that case is it important to be explicit rather than relying on destructors?
The order of destruction is well-specified so that you can rely on it.
Also, can destruction be delayed by the compiler in any case?
No. If it did, that would break a lot of RAII-based code (your MutexLock
class is a very good example of that).