首页 > 解决方案 > __attribute__((destructor)):全局向量变量中的值在主析构函数中被破坏

问题描述

问题:在主析构函数(即“after_main()”函数)中无法访问全局向量 t1 的值。可以访问其他类型的全局变量值。

我尝试过的 PFB 代码并输出:

  1. 声明的全局向量 t1。
  2. 在主函数中添加 t1 中的值
  3. 当在“after_main()”函数中打印值时,它会打印垃圾值。
  4. 打印尺寸时,它会显示“after_main()”函数内矢量的正确尺寸。

从第 3 点和第 4 点开始,我可以说向量没有被破坏,但向量内的值正在被破坏。但我无法理解为什么。

全局变量的生命周期是程序的整个运行时间。因此向量不应该在“after_main()”函数执行期间被破坏。

支持链接:https ://en.wikipedia.org/wiki/Global_variable

问题:

  1. 有人可以解释一下,为什么会发生这种情况,即为什么矢量表现得很奇怪?
  2. 我想访问在“after_main()”函数的 main 期间修改的值(任何动态增长的结构,如向量),有什么解决方案吗?

带动态向量

#include <vector>
#include<iostream>
using namespace std;
void after_main() __attribute__((destructor));
vector<int> t1;
void after_main(){
    cout << t1.size() << endl; //output: 2
    cout << t1[0] << endl; //output: garbage value
    cout << t1[1] << endl; //output: garbage value
}
int main(){
    t1.push_back(10);
    t1.push_back(20);
}

预定义的向量大小

#include <vector>
#include<iostream>
using namespace std;
void after_main() __attribute__((destructor));
vector<int> t1(2);
void after_main(){
    cout << t1.size() << endl; //output:2 
    cout << t1[0] << endl; //output:0
    cout << t1[1] << endl; //output:0
}
int main(){
    t1[0] = 10;
    t1[1] = 20;
}

“after_main()”函数中可访问的全局整数变量示例:

#包括

#include<iostream>
using namespace std;
void after_main() __attribute__((destructor));
int x;
void after_main(){
    cout << x << endl;//output: 5
}
int main(){
    x = 5; 
}

“after_main()”函数中可访问的全局数组变量示例:

#include <vector>
#include<iostream>
using namespace std;
void after_main() __attribute__((destructor));
int x[10];
void after_main(){
    cout << x[0] << endl; //output: 10
    cout << x[1] << endl; // output: 20
}
int main(){
    x[0] = 10;
    x[1] = 20;
}

标签: c++vector

解决方案


推荐阅读