Alex Rivera | Logout

Can you guarantee destructor order when objects are declared on a stack?

Asked 2009-08-07T16:53:20.880
24

I have code that controls a mutex lock/unlock based on scope:

void PerformLogin()
{
    ScopeLock < Lock > LoginLock( &m_LoginLock );

    doLoginCommand();

    ScopeLock < SharedMemoryBase > MemoryLock( &m_SharedMemory );

    doStoreLogin();

    ...
}

Can I guarantee that MemoryLock will be destructed before LoginLock?

Edit
Report

2 Answers

11

Yes, destructors are called in the reverse order of construction.

answered 2009-08-07T16:54:52.983
3

The question was answered already, but I'd like to add that I typically have a habit of writing something like this:

void PerformLogin()
{
    ScopeLock < Lock > LoginLock( &m_LoginLock );
    doLoginCommand();

    {
        ScopeLock < SharedMemoryBase > MemoryLock( &m_SharedMemory );
        doStoreLogin();
        ...
    }
}

In my opinion, this makes the intent clearer (*). That might be relevant if your code really is relying on the specific order. I find that this makes it less likely that someone accidentally changes the order, and causes a hard-to-find bug. (Well, that is of course a non-issue, since we all have tests in place, don't we?)

I always write the redundant parentheses in something like  (a && b) || c  too, and I find this matter quite similar.

(*): Of course, you could use a comment as well.

answered 2009-08-07T21:13:40.653

Your Answer