通过 const 引用传递 constexpr 时编译期间的巨大内存消耗

Huge memory consumption during compilation when passing constexpr by const reference

使用 g++ 编译以下代码会消耗大量内存(超过 5gb)。

#include <iostream>
#define N 100000

struct A {
    int tab[N];
    constexpr A(): tab{} {
        for (size_t i = 0; i < N; ++i) tab[i] = i;
    }
};

struct B {
    int tab[N];
    constexpr B(const A& a): tab{} {
        for (size_t i = 0; i < N; ++i) tab[i] = a.tab[N-1-i] * 2;
    }
};

constexpr A a;
constexpr B b(a);
 
int main(){ std::cout << b.tab[N-5]; }

这似乎是由于在 B 的 constexpr 构造函数中传递了一个 const A& 引起的——按值传递解决了这个问题。 那里发生了什么?

g++ 版本:(Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0。 在一些旧版本上也是如此。

用clang-10编译时不会出现这个问题

似乎已在版本 10.3 和 11 中修复。

https://gcc.gnu.org/bugzilla/show_bug.cgi?id=96197