C++ 级联破坏具有静态存储持续时间的对象
C++ Cascading destructions of objects with static storage duration
this link 表示具有静态存储持续时间的对象的级联破坏是 C++ 中流行的未定义行为。究竟是什么?我不明白。如果能用一个简单的C++程序来说明就更好了。非常感谢您的帮助。谢谢
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
我相信这就是
中未定义行为的含义
Cascading destructions of objects with static storage duration
this link 表示具有静态存储持续时间的对象的级联破坏是 C++ 中流行的未定义行为。究竟是什么?我不明白。如果能用一个简单的C++程序来说明就更好了。非常感谢您的帮助。谢谢
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
我相信这就是
中未定义行为的含义Cascading destructions of objects with static storage duration