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

后端 未结 5 682
-上瘾入骨i
-上瘾入骨i 2021-02-12 14:34

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

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

    doLoginComma         


        
5条回答
  •  既然无缘
    2021-02-12 14:55

    Adding on to Neil's answer.

    Consider if the opposite was true, that is that you couldn't predict the order of destructors for stack declared variables. That would make it nearly impossible to use dependent value types on the stack. Consider

    void Foo() {
      Type1 t1;
      Type2 t2(&t1);
      ...
    }
    

    If C++ did not guarantee destructor ordering, straight forward code like this would be incredibly unsafe because it would be possible for t1 to be destroyed before t2's destructor ran. Hence you could not guarantee t2's destructor ran with a valid t1 value.

提交回复
热议问题