1

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

Community
  • 1
  • 1
Destructor
  • 14,123
  • 11
  • 61
  • 126
  • 2
    It's hard to provide a program demonstrating undefined behavior, as it is ... undefined. – François Moisan Feb 26 '15 at 13:49
  • 1
    @FrançoisMoisan: With so many questions on SO which exhibits UB, it is no so hard to show **source code** with UB. – Jarod42 Feb 26 '15 at 14:20
  • @FrançoisMoisan I believe OP wants an example/explanation of "cascading destructions of objects with static storage duration", not an example of undefined behaviour. It's far from obvious what it means. – molbdnilo Feb 26 '15 at 14:21
  • @Jarod42. Fair enough. My point was that it's gonna be hard to demonstrate what the behavior of that code is. I'm not certain of what one could learn if you can't expect any result from such code. – François Moisan Feb 26 '15 at 14:40

1 Answers1

1

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

Drax
  • 12,682
  • 7
  • 45
  • 85