1

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

4

1 回答 1

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

我相信这就是未定义行为的含义

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

于 2015-02-26T16:38:48.937 回答