I have a quite simple code example which crashes when optimized with -O2
under gcc 8.2.0
#include <vector>
#include <functional>
#include <iostream>
template<typename T, typename Container>
class Lambda_Expression
{
using Lambda = std::function<T()>;
const Lambda & _lambda;
public:
Lambda_Expression(const Lambda & l) : _lambda(l) {}
T operator[](const std::size_t i)
{
std::cerr << "inside expression [] " << i << std::endl;
return _lambda();
}
};
auto lambda = []() -> double
{
return 1.0;
};
int main()
{
int N = 10;
std::vector<double> res(N, 0.0);
double x = lambda();
std::cerr << "before for loop " << x << std::endl;
auto test_expression = Lambda_Expression<double, std::vector<double>>(lambda);
for( int idx=0; idx<N; ++idx )
{
std::cerr << "loop " << idx << std::endl;
double x = test_expression[idx];
}
}
Using also -std=c++17
, in case that makes a difference.
I get
before for loop 1
loop 0
inside expression [] 0
[1] 5288 segmentation fault ./bench_lambdas
whereas I would expect the loop to run for 10 iterations. This segfault does not appear with optimization level less than 2.
The above example looks like fairly harmless code to me and as far as I know level 2 optimizations should not break correct code.
Question: Is there undefined behaviour or incorrect code in my example or what might be the issue?