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

C++ Cascading destructions of objects with static storage duration

本文关键字:C++ 级联 对象 静态 存储 持续时间      更新时间:2023-10-16

此链接介绍了具有静态存储持续时间的对象的级联破坏是C++中流行的未定义行为。它到底是什么?我不能理解。如果用一个简单的C++程序来解释它,它会更好。非常感谢你的帮助。感谢

静态销毁.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;
};

静态破坏.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)
{
}

静态破坏2.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

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

具有静态存储持续时间的物体的级联破坏