I've got the following code:
#include <iostream>
template<typename T>
struct A
{
T a;
T b;
static bool(*foo)(T, T);
};
template<>
bool(*A<int>::foo)(int, int) = [](int a, int b)->bool{ return a == b; };
struct B
{
int b;
};
template<typename T, typename U>
T bar(U(*func)(const int&)) { return func(23).b; }
int main()
{
A<int> a = {.a=1, .b=1};
std::cout << std::boolalpha << A<int>::foo(a.a, a.b) << std::endl;
std::cout << bar<int, B>([](const int& val) -> B { return {.b = val}; });
return 0;
}
Being compiled with -Werror=nonnull -Og -fsanitize=undefined -std=c++20 flags under gcc 11.1 it produces a error per lambda like:
<source>:12:71: error: 'this' pointer is null [-Werror=nonnull]
(for more details see https://godbolt.org/z/a4GsPW71E)
As I know, this = nullptr is a vivid marker of UB in the code, however my code looks pretty inconspicuous. To avoid the error you should either change version of compiler or make a slight change in the code (e.g. remove lambda's parameter, or template, or something else).
Does anyone know the reason of this errors, does gcc try to help me or it is just a bug in the compiler?