Home > Back-end >  Destruction order between globals and static function locals
Destruction order between globals and static function locals

Time:12-27

My understanding is that the order of destruction of objects with static storage duration is the inverse of the order of their initialization.

In this code snippet:

#include <iostream>

class LogValuesObj {
public:
    LogValuesObj() {
        std::cout << "LogValuesObj" << std::endl;
    }
    ~LogValuesObj() {
        std::cout << "~LogValuesObj" << std::endl;
    }
};

void logValues() {
    static LogValuesObj o;
    std::cout << "logValues function called" << std::endl;
}

class EarlyInitLogValues {
public:
    EarlyInitLogValues() {
        std::cout << "EarlyInitLogValues" << std::endl;
        logValues();
    }
    ~EarlyInitLogValues() {
        std::cout << "~EarlyInitLogValues" << std::endl;
    }
};

EarlyInitLogValues e;


int main() {
    return 0;
}

The output on my compiler is:

EarlyInitLogValues
LogValuesObj
logValues function called
~EarlyInitLogValues
~LogValuesObj

In this case, the destruction order is the same as the init order, I expected it to be reversed. If both the global 'e' and the function static local 'o' have static storage duration, why is the destruction order not reversed?

CodePudding user response:

It is well-known that objects with static storage duration are destroyed in the reverse order of their construction. But to be more specific—and since it matters in your case—they are destroyed in the reverse order of the completion of their initialization. See [basic.start.term]/3.

In your case, the initialization of o will complete before the initialization of e. Therefore, e is destroyed before o.

  •  Tags:  
  • c
  • Related