C ++具有静态存储持续时间的对象的级联破坏

时间:2015-02-26 13:42:01

标签: c++ destructor undefined-behavior object-destruction

this链接说关于具有静态存储持续时间的对象的级联破坏是C ++中流行的未定义行为。究竟是什么?我无法理解。如果用简单的C ++程序解释它可以证明这一点会更好。非常感谢您的帮助。谢谢

1 个答案:

答案 0 :(得分: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;

由于编译单元中静态对象的销毁顺序是未定义的(实际上它是未定义的构造顺序,但结果是相同的,因为销毁顺序是构造的相反顺序),在我的机器上取决于顺序我编译它给我不同输出的文件:

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

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

我相信这是

中未定义行为的含义
  

具有静态存储持续时间的对象的级联破坏