Search code examples
c++destructorundefined-behaviorobject-destruction

C++ Cascading destructions of objects with static storage duration


this link says about cascading destructions of objects with static storage duration is popular undefined behaviour in C++. What is it exactly? I can't understand. It will be more good if it is explained with a simple C++ program that can demonstrate this. Your help is greatly appreciated. Thanks


Solution

  • static_destruction.h

    #include <vector>
    
    class   first
    {
    public:
      static std::vector<int> data;
    
    public:
      first();
      ~first();
    };
    
    class   second
    {
    public:
      static std::vector<int> data;
    
    public:
      second();
      ~second();
    };
    
    class   container
    {
    public:
      static first  f;
      static second s;
    };
    

    static_destruction.cpp

    #include <iostream>
    #include "static_destruction.h"
    
    first::first()
    {
      data = {1, 2, 3, 4};
    }
    
    first::~first()
    {
      std::cout << second::data.size() << std::endl;
    }
    
    std::vector<int>        first::data;
    
    second   container::s;
    
    int     main(void)
    {
    }
    

    static_destruction2.cpp

    #include <iostream>
    #include "static_destruction.h"
    
    second::second()
    {
      data = {1, 2, 3, 4, 5, 6};
    }
    
    second::~second()
    {
      std::cout << first::data.size() << std::endl;
    }
    
    std::vector<int> second::data;
    
    first   container::f;
    

    Since the destruction order of static objects across compilation units is undefined (actually it's the construction order which is undefined but the result is the same since destruction order is the inverse order of construction), on my machine depending on the order in which i compile the files it gives me different outputs:

    $> g++ -std=c++11 static_destruction.cpp static_destruction2.cpp
    $> ./a.out
    0
    4
    

    and

    $> g++ -std=c++11 static_destruction2.cpp static_destruction.cpp
    $> ./a.out
    0
    6
    

    I believe thats what is meant by undefined behaviour in

    Cascading destructions of objects with static storage duration