我想知道 Clang 或 GCC 中是否有任何优化选项可用于std::vector
C++ 中的转义分析。因为std::vector<int>
在下面的示例中,不需要v
在堆或堆栈中分配实际数据。编译器实际上可以在堆栈上分配v.data()
以获得更好的性能。
假设 Clang/GCC 不做逃逸分析,是否有什么特别的动机不使用逃逸分析?
假设 Clang/GCC 进行了逃逸分析,为什么 value of
v.data()
和&x
这么不同?
#include<cstdio>
#include<vector>
int main() {
int x = 0;
std::vector<int> v(3, 0);
std::printf("&x: %p\n", &x);
//std::printf("&v: %p\n", &v); // we intentionally don't print the pointer to v here.
std::printf("v.data(): %p\n", v.data());
return x + v[0]; // we want compiler not to optimize everything out
}
预期结果
&x: <some address>
v.data(): <some address> + 4
Clang 和 GCC 的实际结果
[*****@localhost test]$ g++ test.cc -O3
[khanh@localhost test]$ ./a.out
&x: 0x7ffe2af5a59c
v.data(): 0xadde70
[*****@localhost test]$ clang++ test.cc -O3
[*****@localhost test]$ ./a.out
&x: 0x7fff66ce1ab4
v.data(): 0xfeee70
谢谢!