问题描述
在C ++中以什么顺序调用全局对象的构造函数?
In what order get the constructors of global object in C++ called?
这个问题出现在管理某些使用者的内存需求的内存池的上下文中。我看到了一个相当大的源代码,它在全局名称空间中定义了一些仅使用堆函数的使用者。应该添加一个内存池而不更改使用者的名称空间。因此,我在全局名称空间中添加了一个池类和一个定义,并修改了每个使用者类以从 thePool类的实例获取内存。不幸的是,在执行的最后,当调用所有全局析构函数时,我得到了一个很好的段错误。 gdb backtrace显示到pool :: free的分支会产生segfault。这对我来说听起来很奇怪。但是,我将其简化为一个非常简单的池/消费者示例,该示例位于全局名称空间中。不幸的是,这并没有重现段错误-池的析构函数在使用者的所有析构函数之后被调用。这是纯粹的运气,还是对g ++ 4.5的良好教育?
This question arises in the context of a memory pool that manages the memory needs for some consumers. I was presented with a rather large source code which defines at global namespace some consumers just using heap functions. A memory pool should be added without changing the namespace of the consumers. So, I added a pool class and a definition at global namespace and modified each consumer class to get memory from the instance of the class "thePool". Unfortunately at the end of the execution when it comes to call all global destructors I get a nice segfault. gdb backtrace shows that the branch to pool::free produces the segfault. This sounds odd to me. However, I boiled it down to a very simple pool/consumer example which lives on the global namespace. Unfortunately this does not reproduce the segfault -- the destructor of pool gets called after all destructors of the consumer. Is this pure luck, or a well-educated guess of g++ 4.5 ?
下面是简化的示例:
#include<iostream>
using namespace std;
struct pool {
pool() {
cout << "pool::pool" << endl;
}
~pool() {
cout << "pool::~pool" << endl;
}
void get() {
cout << "pool::get" << endl;
}
void free() {
cout << "pool::free" << endl;
}
};
pool thePool;
struct consumer {
~consumer() {
cout << "consumer::~consumer" << endl;
thePool.free();
}
consumer() {
cout << "consumer::consumer" << endl;
thePool.get();
}
};
consumer a,b;
int main() {
}
输出为:
pool::pool
consumer::consumer
pool::get
consumer::consumer
pool::get
consumer::~consumer
pool::free
consumer::~consumer
pool::free
pool::~pool
不错!就像我想要的那样。真是运气?我的意思是在销毁消费者a或b之前可以调用pool dtor,对吗?
Nice! Just as I wanted it. Pure luck? I mean the dtor of pool could have been called before destroying consumer a or b, right?
要回答的问题是:全局对象的缺点是什么顺序?
The question to answer is: "In what order are the cons of global objects called?"
推荐答案
全局变量按照声明的顺序初始化。因此,它们的构造函数将以初始化时的相同顺序被调用。在一个中,这是正确的。但是,语言规范未定义跨多个翻译单元的初始化顺序。
Global variables are initialized in the order in which they're declared. So their constructor will be called in the same order in which they're initialized. This is true within one translation unit. However, the initialization order across multiple translation-units is not defined by the language specification.
它们的析构函数将按照其初始化的相反顺序进行调用。
And their destructors are called in the reverse order of their initialization as usual.
这篇关于全局构造函数的调用顺序是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!