简体   繁体   English

C++ 编译大型结构时内存使用过多

[英]C++ Excessive memory usage when compiling large structs

Yesterday I was coding when I found some weird C++ compiler behavior.昨天我在编码时发现了一些奇怪的 C++ 编译器行为。

This code compiles effortlessly on my computer using g++ 7.2.0:此代码使用 g++ 7.2.0 在我的计算机上轻松编译:

#include <iostream>

const int SIZE = 1e6;

struct ArrayOfInts
{
    int a[SIZE];
} array_of_ints;

int main()
{
    std::cout << array_of_ints.a[0];
    return 0;
}

However this code is different:但是这段代码是不同的:

#include <iostream>
#include <functional>

const int SIZE = 1e6;

struct ArrayOfPairs
{
    std::pair<int, int> a[SIZE];
} array_of_pairs;

int main()
{
    std::cout << array_of_pairs.a[0].first;
    return 0;
}

It takes noticeably longer to compile.编译时间明显更长。 When looking at Task Manager, I notice that "cc1plus.exe" memory usage jumps to ~500 MB while compiling this snippet of code.在查看任务管理器时,我注意到“cc1plus.exe”内存使用量在编译这段代码时跳到了大约 500 MB。 Yesterday when I set the size to 1e7, my computer froze.昨天当我把大小设置为 1e7 时,我的电脑死机了。

I don't understand why this happened because the array of pairs only needs ~4 MB of memory, yet it is taking more than 100 times of the memory to compile.我不明白为什么会发生这种情况,因为成对数组只需要约 4 MB 的内存,但编译需要 100 多倍的内存。

I've tested on some online sites with versions of g++ different from mine and they also take a lot of time to compile.我已经在一些在线网站上测试过 g++ 版本与我不同的版本,它们也需要很多时间来编译。

Of course there are many ways to circumvent this problem, but it feels kind of annoying when you make some mistake in your code and your computer freezes when compiling.当然有很多方法可以绕过这个问题,但是当你在代码中犯了一些错误并且你的计算机在编译时死机时感觉有点烦人。

So I want to ask where does the problem originate from?所以我想问一下问题出在哪里? Is it C++ or g++ or my fault?是 C++ 还是 g++ 还是我的错? My guess is that it has something to do with std::pair not being a POD type.我的猜测是它与 std::pair 不是 POD 类型有关。

The problem seems to happen in GCC 7.3 (and older) and Clang 3.3 (and older).该问题似乎发生在 GCC 7.3(及更早版本)和 Clang 3.3(及更早版本)中。 You can easily test these cases with Godbolt's compile explorer, see: https://godbolt.org/g/1f2WUi您可以使用 Godbolt 的编译资源管理器轻松测试这些案例,请参阅: https ://godbolt.org/g/1f2WUi

You will see that it compiles effortlessly with GCC 8.1+ and Clang 3.4+, but it fails (timeout) with older versions.您会看到它可以轻松地使用 GCC 8.1+ 和 Clang 3.4+ 进行编译,但使用旧版本会失败(超时)。 They can even handle the SIZE = 1e7 value you mentioned.他们甚至可以处理您提到的SIZE = 1e7值。 I have tried some optimization parameters (eg, -O3) but they don't seem to have an influence on such issue.我尝试了一些优化参数(例如,-O3),但它们似乎对此类问题没有影响。 So maybe you should upgrade your compiler version in order to solve this particular problem.因此,也许您应该升级编译器版本以解决此特定问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM