c++ - __attribute__((destructor)):全局向量变量中的值在主析构函数中被破坏
问题描述
问题:在主析构函数(即“after_main()”函数)中无法访问全局向量 t1 的值。可以访问其他类型的全局变量值。
我尝试过的 PFB 代码并输出:
- 声明的全局向量 t1。
- 在主函数中添加 t1 中的值
- 当在“after_main()”函数中打印值时,它会打印垃圾值。
- 打印尺寸时,它会显示“after_main()”函数内矢量的正确尺寸。
从第 3 点和第 4 点开始,我可以说向量没有被破坏,但向量内的值正在被破坏。但我无法理解为什么。
全局变量的生命周期是程序的整个运行时间。因此向量不应该在“after_main()”函数执行期间被破坏。
支持链接:https ://en.wikipedia.org/wiki/Global_variable
问题:
- 有人可以解释一下,为什么会发生这种情况,即为什么矢量表现得很奇怪?
- 我想访问在“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;
}
解决方案
推荐阅读
- floating-point - “p”在浮点数的指数十六进制表示法中代表什么
- upgrade - 当 Storm 客户端从 0.10 升级到 1.1.0 时,Storm 拓扑部署失败并出现 IllegalArgumentException
- php - 如何将其他数据传递给 Laravel Socialite 中的回调方法?
- logstash-configuration - 使用 Logstash 配置文件添加小时数
- java - 引用 Jar 到日志文件的所有消息 + 设置日志文件编码为 UTF-8 以显示日文字符 (Log4j2)
- android - Android + ObjectBox 搜索查询问题
- java - 如何使用 charAt 和 string.length() 分割字符串
- python - Pandas:基于复杂逻辑删除具有特定字符串的行和列
- excel - 如何在单个列中查找范围以区分字符串
- python - 如何访问在烧瓶中查看随机创建的文件夹?