Is a C++ destructor guaranteed not to be called until the end of the block?

后端 未结 8 1976
孤街浪徒
孤街浪徒 2021-01-03 18:03

In the C++ code below, am I guaranteed that the ~obj() destructor will be called after the // More code executes? Or is the compiler allowed to destruct the

8条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-03 18:25

    Destruction in C++ is deterministic - meaning that the compiler is not free to move that code around. (Of course optimization might inline the destructor, determine that the destructor code does not interact with // More code and do some instruction reordering, but that's another issue)

    If you couldn't depend on the destructors being called when they are supposed to be called, you couldn't use RAII to grab locks (or just about any other RAII construct for that matter):

    {
        LockClass lock(lockData);
        // More code
    } // Lock automatically released.
    

    Also, you can depend on destructors running in reverse order of how the objects were constructed.

提交回复
热议问题